I want to group the following data table by var1 and var2 and then find the percentage in var2:
var1
var2
data <- as.data.table(l
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