Home > Software design >  R - Percentage of whole dataframe per column
R - Percentage of whole dataframe per column

Time:10-28

I have a data frame reporting the count of answers per question (this is just a part of it), and I'd like to obtain the answer percentage for each question. I've found adorn_percentages, but it computes the percentage by dividing the values for the whole data frame, meanwhile, I just want the percentage for each column. Each column has a total of 2230 answers. I was thinking to use something like (x/2230)*100 but I don't know how to go on.

df<-data.frame(q1=c(159,139,1048,571,93), q2=c(106,284,1043,672,125), q3=c(99,222,981,843,94))

   q1   q2  q3
1  159  106  99
2  139  284 222
3 1048 1043 981
4  571  672 843
5   93  125  94

CodePudding user response:

We may use colSums to do the division after making the lengths same

100 * df/colSums(df)[col(df)]

or use sweep

100 * sweep(df, 2, colSums(df), `/`)

Or use proportions

df[paste0(names(df), "_prop")] <- 100 * proportions(as.matrix(df), 2)

-output

> df
    q1   q2  q3   q1_prop   q2_prop   q3_prop
1  159  106  99  7.910448  4.753363  4.421617
2  139  284 222  6.915423 12.735426  9.915141
3 1048 1043 981 52.139303 46.771300 43.814203
4  571  672 843 28.407960 30.134529 37.650737
5   93  125  94  4.626866  5.605381  4.198303
  • Related