如何根据自定义函数将 NA 移除合并到聚合中?

How can I incorporate NA removal into aggregate based on a custom function?

这是我第一次使用任何自定义函数,请多多包涵。我为标准错误创建了一个函数,我想将其与 aggregate 一起使用。它一直有效,直到我试图排除 NA。

要使用的虚拟数据框:

se <- function(x) sd(x)/sqrt(length(x))
df <- data.frame(site = c('N','N','N','S','S','S'),
                birds = c(NA,4,2,9,3,1), 
                worms = c(2,1,2,4,0,5))
means <- aggregate(df[,2:3], na.rm = T, list(site = df$site), FUN = mean)
error <- aggregate(df[,2:3], na.rm = T, list(site = df$site), FUN = se)

所以 aggregate 在我排除 NA 之前起作用(例如 error <- aggregate(df[,2:3], list(site = df$site), FUN = se)),并且它在求平均值时起作用(使用其余值取平均值并忽略缺失值)。使用我的自定义 se 函数时,如何以相同的方式排除 NA?

问题是您在 se 函数中没有 na.rm 的显式参数。如果将其添加到您的函数中,它应该可以工作:

se <- function(x, na.rm = TRUE) {
    sd(x, na.rm = na.rm)/sqrt(sum(!is.na(x)))
}