[英]r - Handling NA values in summary stats
情况
我目前正在使用ddply
和numcolwise(summary)
返回给定数据帧的5个摘要状态(即min
, Q1
, Q2
, mean
, Q3
和max
)。
但是我不知道如何处理NA
(尝试过rm.na=TRUE
各种组合。
这是一个示例数据帧,以及我如何使用ddply
和numcolwise(summary)
。
library(dplyr)
id <- c(1, 2, 3, 4, 5)
name <- c("name1", "name2", "name3", "name4", "name5")
position <- c("AAA", "BBB", "CCC", "AAA", "BBB")
salary <- c(20, 30, 40, 50, 60)
bonus <- c(1, 1, 1, NA, 1)
sti <- c(2, 3, 4, 5, 6)
lti <- c(6, 5, 4, 3, 2)
other <- c(10, 11, 12, 13, 14)
df <- data.frame(id, name, position, salary, bonus, sti, lti, other)
df_out <- ddply(df, .(position), numcolwise(summary))
题
是否可以通过这种方式使用numcolwise(summary)
来处理NA
,或者是否有一种方法/函数可以为我提供每个数值列的5个统计信息?
笔记
这些功能都起作用
min(df[,"bonus"], na.rm=TRUE)
median(df[,"bonus"], na.rm=TRUE)
mean(df[,"bonus"], na.rm=TRUE)
quantile(df[,"bonus"], probs=(c(0.25, 0.5, 0.75)), type=7, na.rm=TRUE)
summary(df[,"bonus"], na.rm=TRUE)
更新
经过一些研究,一种可能但不是很好的解决方案是
df[,c("position", "salary","bonus","sti","lti","other")] %>%
group_by(position) %>%
summarise_each(funs(min, quantile(.,0.25, na.rm=TRUE),
quantile(.,0.5, na.rm=TRUE), mean, quantile(., 0.75, na.rm=TRUE), max))
我可以使用%>%
表示法summarise_each()
并在funs
参数中指定函数来实现结果。
df[,c("position", "salary","bonus","sti","lti","other")] %>%
group_by(position) %>%
summarise_each(funs(min, quantile(.,0.25, na.rm=TRUE),
quantile(.,0.5, na.rm=TRUE), mean, quantile(., 0.75, na.rm=TRUE), max))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.