[英]dplyr count, sum and calculate the percentage and round to whole number using R
我懇請幫助按 ID 分組、計算非零並將結果顯示為該特定 ID 我的數據中總數的百分比
library(dplyr)
id<-c(1,1,1,1,1,2,2,2,2)
x<-c(0,1,0,1,0,0,0,1,0)
df1<-data.frame(id,x)
head(df1)
在我的結果中,在按 id=1 分組后,我需要列的總數為 2,另一列的百分比(2/5)= 40。對於組 id=2,我需要列的總數為 1百分比為 (1/4)=25
df1 %>%
group_by(id) %>%
summarise(sum_of_1 = sum(x!=0),
pct= round((sum_of_1/n())*100))
這個有效。 感謝綠巨人的幫助
嘗試這個-
df1 %>%
group_by(id) %>%
summarise(sum_of_1 = sum(x, na.rm = TRUE),
pct = round((sum_of_1/n())*100))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.