2017-02-16 191 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))