Sam Mwenda
Sam Mwenda

Reputation: 154

dplyr count, sum and calculate the percentage and round to whole number using R

I kindly request for help in grouping by ID, counting non-zeros and presenting the results as the percentage of the total in that particular ID My data

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)

in my results, after grouping by id=1, then i need column with total for ones as 2 and another column with the precentage (2/5)= 40. For group id=2 then i need the total for the column as 1 and percentage as (1/4)=25

Upvotes: 0

Views: 976

Answers (2)

Sam Mwenda
Sam Mwenda

Reputation: 154

df1 %>%
  group_by(id) %>%
  summarise(sum_of_1 = sum(x!=0),
            pct= round((sum_of_1/n())*100))

This one works. Thanks for the help Hulk

Upvotes: 1

akash ansari
akash ansari

Reputation: 66

Try this-

df1 %>%
  group_by(id) %>%
  summarise(sum_of_1       = sum(x, na.rm = TRUE),
            pct            = round((sum_of_1/n())*100)) 

Upvotes: 0

Related Questions