我有一个数据框,我有不同的月份,我想在开始月份(在开始变量中)和结束月份(在结束变量中)之间的每一行的平均值
nom <- letters[1:5]
pseudo <- paste(nom, 21:25, sep = "")
janvier <- c(0, 1, 1, 1, 0)
fevrier <- c(1, 1, 1, 1, 1)
mars <- c(0, 0, 0, 1, 1)
avril <- c(1, 1, 1, 0, 1)
mai <- c(1, 0, 1, 1, 1)
juin <- c(1, 1, 0, 1, 0)
df <- data.frame(nom =nom, pseudo = pseudo, janvier = janvier,
fevrier = fevrier, mars = mars, avril = avril,
mai = mai, juin = juin)
dfm <- as.matrix(df[, -c(1, 2)])
my_matrix <- matrix(nrow = 10, ncol = 6)
my_matrix <- matrix("no info", nrow = 5, ncol = 2)
colnames(my_matrix) <- c("begin", "end")
for(i in 1:dim(dfm)[1]){
for(j in 1:(dim(dfm)[2]-2)){
if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
my_matrix[i, 1] <- colnames(dfm)[j]
my_matrix[i, 2] <- colnames(dfm)[j+2]
break
}
}
}
output <- cbind(df, my_matrix)
output %>%
filter(begin != "no info") -> output
我尝试用矢量化方法做,例如:
output$mean <- rowMeans(output[, output$begin:output$end])
我也试过这个,但似乎没有认出我的开始变量:
for(i in seq_len(nrow(output))){
for(j in seq_len(ncol(output))){
output$mean[i, j] <- rowMeans(as.character(begin[i, j]):as.character(end[i, j]))
}
}
我不想在dplyr包中使用循环,感谢您的帮助
编辑:我不想要group_by,我的问题有点复杂,因为我必须在存储在开始和结束变量中的变量之间进行排序
答案 0 :(得分:2)
如果我理解正确,您需要将所有内容切换为长格式。然后你可以加入,过滤,分组和平均:
## long format
library(reshape2)
df_long = melt(dfm)
names(df_long) = c("id", "month", "value")
id_key = as.data.frame(my_matrix)
id_key$id = 1:nrow(id_key)
## turn the months into a factor with the correct order
month_levs = c("janvier", "fevrier", "mars", "avril", "mai", "juin")
id_key = mutate(id_key, begin = factor(begin, levels = month_levs),
end = factor(end, levels = month_levs))
df_long = mutate(df_long, month = factor(month, levels = month_levs))
## calculate results
results = df_long %>% left_join(id_key) %>%
group_by(id) %>%
filter(between(as.numeric(month), as.numeric(begin), as.numeric(end))) %>%
summarize(mean = mean(value))
results
## A tibble: 3 x 2
# id mean
# <int> <dbl>
# 1 1 1
# 2 4 1
# 3 5 1