Find a percentage based on multiple columns of criteria in R

后端 未结 3 470
眼角桃花
眼角桃花 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:38

    You can create your proportion format function:

    prop_format <- 
    function (x, digits=4) 
    {
      x <- round(x/sum(x), digits)*100
      paste0(x,'%')
    }
    

    Then using ave :

    ave(dt$variable,list(dt$ST,dt$cd),FUN=prop_format)
    
    [1] "90.9%"  "9.1%"   "25.23%" "9.73%"  "65.05%" "29.91%" "70.09%"
    

提交回复
热议问题