Find a percentage based on multiple columns of criteria in R

后端 未结 3 468
眼角桃花
眼角桃花 2021-01-22 08:13

I have multiple columns and I would like to find the percentage of a one column in the other columns are the same. For example;

ST  cd  variable
1   1   23432
1         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-22 08:47

    library(data.table)
    
    DT <- data.table(read.table(text = "ST  cd  variable
    1   1   23432
    1   1   2345
    1   2   908890
    1   2   350435
    1   2   2343432
    2   1   9999
    2   1   23432 ", header = TRUE))
    
    DT[, percentage := variable / sum(variable) , by = list(ST, cd)]
    
    ##    ST cd variable percentage
    ## 1:  1  1    23432 0.90902743
    ## 2:  1  1     2345 0.09097257
    ## 3:  1  2   908890 0.25227624
    ## 4:  1  2   350435 0.09726856
    ## 5:  1  2  2343432 0.65045519
    ## 6:  2  1     9999 0.29909366
    ## 7:  2  1    23432 0.70090634
    

提交回复
热议问题