百分比计算与行
问题描述:
在一定条件一栏我有以下数据框:百分比计算与行
sleep health count prop
1 7 Good 100 NA
2 7 Normal 75 NA
3 7 Bad 25 NA
4 8 Good 125 NA
5 8 Normal 75 NA
6 8 Bad 25 NA
我想基于sleep
组count
一个百分点,以填补prop
列。例如,前3行prop
应该是0.5,0.375和0.125,那么最后3行分别是0.555,0.333和0.111。
这可以通过手动通过sleep
第一分隔数据帧,然后使用prop.table(prop)
每个来完成,但由于有众多sleep
组我不能找到一种简洁的方式来做到这一点。有什么想法吗?
答
在R
,我们可以通过 '睡眠'
library(dplyr)
df1 %>%
group_by(sleep) %>%
mutate(prop = round(count/sum(count), 3))
# sleep health count prop
# <int> <chr> <int> <dbl>
#1 7 Good 100 0.500
#2 7 Normal 75 0.375
#3 7 Bad 25 0.125
#4 8 Good 125 0.556
#5 8 Normal 75 0.333
#6 8 Bad 25 0.111
或者使用base R
df1$prop <- with(df1, ave(count, sleep, FUN=prop.table))
[dplyr的可能的复制分组后由 '计数' 的
sum
将做到这一点:使用group \ _by并总结]在子组中查找百分比(http://*.com/questions/29549731/dplyr-finding-percentage-in-a-sub-group-using-group-by-and-总结)或[总结按子组百分比在R](http://*.com/questions/27134516/summarizing-by-subgroup-percentage-in-r) –