我有一些数据包含年度观察结果,有些州只有月度数据,有些州有两种。我想使用年度观察,但如果不存在年度则使用月平均值。我可以运行一个循环,但这似乎效率低下。有更好的方法吗?
示例数据
newdat <- data.frame(state = c("co", "co", "co", "co", "co", "co"), year = c(2000,2000,2000,2001,2001,2001),
type = c("year", "month", "month", "month", "month", "month"),
value = c(6,6,10,5,2,9))
所需的输出
state year type value
1 co 2000 year 6.0
2 co 2001 year 5.3
答案 0 :(得分:2)
也许
library(tidyverse)
newdat %>%
group_by(state, year) %>%
summarise(
value = ifelse(
"year"%in%type,
value[type=="year"],
mean(value[type=="month"])),
type="year")
# # A tibble: 2 x 4
# # Groups: state [?]
# state year value type
# <fctr> <dbl> <dbl> <chr>
# 1 co 2000 6.000000 year
# 2 co 2001 5.333333 year