使用 tapply 时处理 NA

deal with NA's when using tapply

考虑以下示例:

Factor <- c(rep('Male', 10),rep('Female', 10))
Age <- sample(30:80,20)

df1 <- data.frame(Factor, Age)

with(df1, tapply(Age, Factor, mean))

最后一条命令为我们提供了男女的平均年龄。现在假设一个 inout 标有 NA。我们如何克服这个问题?

df1$Age[15] <- NA
with(df1, tapply(Age, Factor, mean))

您可以传递在 tapply 中使用的函数的参数,在本例中为 mean

如果您查看 ?mean,您会发现 mean 的默认值为 na.rm = False。只需更改它:

tapply(df1$Age, df1$Factor, mean, na.rm = T)

或者,使用 with:

with(df1, tapply(Age, Factor, mean, na.rm = T))