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

后端 未结 5 953
遇见更好的自我
遇见更好的自我 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 02:05

    Given this:

    > d = data.frame(sample=c("a2","a3"),a=c(1,5),b=c(4,5),c=c(6,4))
    > d
      sample a b c
    1     a2 1 4 6
    2     a3 5 5 4
    

    You can replace every column other than the first by applying over the rest:

    > d[,-1] = apply(d[,-1],2,function(x){x/sum(x)})
    
    > d
      sample         a         b   c
    1     a2 0.1666667 0.4444444 0.6
    2     a3 0.8333333 0.5555556 0.4
    

    If you don't want d being stomped on make a copy beforehand.

提交回复
热议问题