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

前端 未结 4 827
后悔当初
后悔当初 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条回答
  •  旧时难觅i
    2021-01-15 02:49

    I like the plyr for these tasks as they allow you to specify the format of the output. You can turn this into a function that will scale to more columns and different base levels for the division easily.

    FUN <- function(dat, baseRow = 1){
        require(plyr)   
        divisors <- dat[baseRow ,]
        adply(dat, 1, function(x) x / divisors)
    }
    
    FUN(trqldnum, 1)
    
      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
    

提交回复
热议问题