R: Building function to calculate % relative frequency and apply them over all columns

Viewed 400

I am a complete beginner in R and having some problems with building functions...

enter image description here

My data looks like this.

I would like to build a function so that I can convert all values in the table into % relative frequency per column.

For example, for first column, I would like divide all the values in that column by columnn sum (colSum) of that column.

Then, I would like to repeat that over all columns.

Is there any functions I can look into? I tried apply function, but I couldn't get it to work.

Thank you:)

3 Answers

Using apply function, you can do:

apply(df,2, function(x) x/sum(x)*100)

Here, I created this dummy example to illustrate how it works:

 df <- data.frame(C1 = sample(1:100,5),
                   C2 = sample(1:100,5),
                   C3 = sample(1:100,5))

apply(df,2, function(x) x/sum(x)*100)

            C1        C2       C3
[1,] 32.903226 13.861386 19.59799
[2,] 27.096774  1.980198 16.33166
[3,]  3.870968 44.554455 17.58794
[4,] 15.483871 17.821782 21.85930
[5,] 20.645161 21.782178 24.62312  

Using dplyr package, you can get the same output by using mutate_all:

library(dplyr)
df %>% mutate_all(.funs = ~./sum(.)*100)

         C1        C2       C3
1 32.903226 13.861386 19.59799
2 27.096774  1.980198 16.33166
3  3.870968 44.554455 17.58794
4 15.483871 17.821782 21.85930
5 20.645161 21.782178 24.62312

Does it answer your question ?

Another base R option could be:

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

We can replicate the colSums to keep the lengths same before doing the division in base R

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