How to group by different columns and find the percentage based on one column?

后端 未结 1 1444
忘掉有多难
忘掉有多难 2021-01-26 16:03

I want to group the following data table by var1 and var2 and then find the percentage in var2:

data <- as.data.table(l         


        
相关标签:
1条回答
  • 2021-01-26 16:36

    This should give you what you want:

    data <- data[, .N, by = .(var1, var2)][, ratio:=N/sum(N), by = var2]
    

    which results in:

    > data
       var1 var2 N     ratio
    1:   x1   y1 2 0.6666667
    2:   x2   y1 1 0.3333333
    3:   x1   y2 1 0.5000000
    4:   x2   y2 1 0.5000000
    
    0 讨论(0)
提交回复
热议问题