Dividing each cell in a data set by the column sum in R

后端 未结 5 947
遇见更好的自我
遇见更好的自我 2020-12-17 01:35

I am trying to divide each cell in a data frame by the sum of the column. For example, I have a data frame df:

sample   a   b   c
a2      1    4    6
a3             


        
5条回答
  •  伪装坚强ぢ
    2020-12-17 01:56

    You could do this in dplyr as well.

    sample <- c("a2", "a3")
    a <- c(1, 5)
    b <- c(4, 5)
    c <- c(6, 4)
    dat <- data.frame(sample, a, b, c)
    dat
    
    library(dplyr)
    
    dat %>%
        mutate(
            a.PCT = round(a/sum(a), 3),
            b.PCT = round(b/sum(b), 3),
            c.PCT = round(c/sum(c), 3))
    
      sample a b c a.PCT b.PCT c.PCT
    1     a2 1 4 6 0.167 0.444   0.6
    2     a3 5 5 4 0.833 0.556   0.4
    

提交回复
热议问题