使用tapply

时间:2017-01-19 17:11:44

标签: r 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))

1 个答案:

答案 0 :(得分:2)

您可以传递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))