2017-02-16 196 views
-2

在一定条件一栏我有以下数据框:百分比计算与行

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 

我想基于sleepcount一个百分点,以填补prop列。例如,前3行prop应该是0.5,0.375和0.125,那么最后3行分别是0.555,0.333和0.111。

这可以通过手动通过sleep第一分隔数据帧,然后使用prop.table(prop)每个来完成,但由于有众多sleep组我不能找到一种简洁的方式来做到这一点。有什么想法吗?

+1

[dplyr的可能的复制分组后由 '计数' 的sum将做到这一点:使用group \ _by并总结]在子组中查找百分比(http://stackoverflow.com/questions/29549731/dplyr-finding-percentage-in-a-sub-group-using-group-by-and-总结)或[总结按子组百分比在R](http://stackoverflow.com/questions/27134516/summarizing-by-subgroup-percentage-in-r) –

回答

-1

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))