apply() and calculating proportion of first row for all dataframe rows

前端 未结 4 795
后悔当初
后悔当初 2021-01-15 02:18

I have a dataframe as shown below listing the number of injuries by vehicle type:

trqldnum <- data.frame(motorveh=c(796,912,908,880,941,966,989,984),
             


        
4条回答
  •  暖寄归人
    2021-01-15 03:05

    Convert the data-frame to a matrix and use matrix operations:

    m <- as.matrix(trqldnum)
    
    trqldprop <- as.data.frame( t(t(m)/m[1,]) )
    
    > trqldprop
      motorveh motorcyc    bicyc
    1 1.000000 1.000000 1.000000
    2 1.145729 1.147860 1.165138
    3 1.140704 1.268482 1.146789
    4 1.105528 1.217899 1.256881
    5 1.182161 1.568093 1.577982
    6 1.213568 1.513619 1.339450
    7 1.242462 1.844358 1.587156
    8 1.236181 1.929961 1.633028
    

    Note that we need to transpose the matrix (see the t(m)) because when you divide a matrix by a vector, the operation is done column-wise.

提交回复
热议问题