我的问题在随附的图片(链接)中进行了解释。
我尝试了以下没有结果的代码:
df[paste0("combined_", df_of_column_names)] <- lapply(df, ave, na.rm =TRUE, df[["index Z"]])
在存在NA的情况下不返回平均值
df[paste0("combined_", df_of_column_names)] <- lapply(df, ave(FUN=function(x) mean(x, na.rm=T)), df[["index Z"]])
出现错误:
FUN(x)中的错误:缺少参数“ x”,没有默认值
有人可以帮我吗?非常感谢!
答案 0 :(得分:0)
没有可重复的示例,很难给出相关答案,但可以尝试一下:
library(dplyr)
df2 <- df %>% # df is your data frame
group_by(`index Z`) %>%
summarise_all(.funs = mean, na.rm = TRUE)
# expected output
left_join(df1[, 1], df2, by = `index Z`)
答案 1 :(得分:0)
使用库dplyr。检查此示例:
df1 %>% group_by(index) %>%
summarise(modreturn1 = mean(return1,na.rm = T), modreturn2 = mean(return2,na.rm = T))
它将返回一个表,该表将前两个变量汇总为它们的均值(NA
除外)。
现在,如果您确实想要与原始数据集一样多的行:
首先,将以上查询保存到名为resumen
的变量中,然后:
merge(df1[,"index"],resumen,all.x = T)
不客气:)
答案 2 :(得分:0)
与ANG类似的答案,但使用data.table
library(data.table)
df <- setDT(df)
df2 <- df[,lapply(.SD,mean), by = `index Z`]
df2[df, on = `index Z`]
答案 3 :(得分:0)
使用基数R,我可以在与您类似的简单情况下使用它。
attach(warpbreaks)
wool[5] <- NA
df <- data.frame(wool = wool, break = breaks)
df <- cbind(df, df$wool)
df
wool breaks breaks.1
1 A 26 26
2 A 30 30
3 A 54 54
4 A 25 25
5 A NA NA
6 A 52 52
...
lapply(df[,-1], function(x) ave(x, df[,1], FUN = function(x) mean(x, na.rm=TRUE)))
$breaks
[1] 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846
[9] 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846
[17] 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846
[25] 29.53846 29.53846 29.53846 25.25926 25.25926 25.25926 25.25926 25.25926
[33] 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926
[41] 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926
[49] 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926
$breaks.1
[1] 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846
[9] 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846
[17] 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846 29.53846
[25] 29.53846 29.53846 29.53846 25.25926 25.25926 25.25926 25.25926 25.25926
[33] 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926
[41] 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926
[49] 25.25926 25.25926 25.25926 25.25926 25.25926 25.25926