Calculate percentages of a binary variable BY another variable in R

后端 未结 4 1678
攒了一身酷
攒了一身酷 2020-12-12 01:37

I want to summarise the percentage of people that have been treated BY region.

I have created a dummy dataset for this purpose:

id <- seq(1:1000)
         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-12 02:26

    If I understand the question correctly, this can be very easily (and fast!) done with table and prop.table:

    prop.table(table(d$treatment, d$region))
    

    This gives you the percentages of each cell. If you want to get row- or column-wise percentages, you want to make use of the margin parameter in prop.table:

    prop.table(table(d$treatment, d$region), margin = 2) # column-wise
    prop.table(table(d$treatment, d$region), margin = 1) # row-wise
    

提交回复
热议问题