Я хотел бы вычислить взвешенные пропорции, если это возможно, используя функции prop.table()
и xtabs()
.
Пример:
library(data.table)
set.seed(1)
n <- 20
X <- data.table(color = sample(c("Blue", "Green", "Red"), n, replace = TRUE),
letter = sample(c("a", "b"), n, replace = TRUE),
number = sample(1:3, n, replace = TRUE),
weight = runif(n))
X[, weight := weight/sum(weight)]
# > X
# color letter number weight
# 1: Blue a 2 0.03300399
# 2: Red a 3 0.08170773
# 3: Blue a 2 0.03374477
# 4: Green a 1 0.03248830
# 5: Blue a 3 0.04636611
# 6: Red b 2 0.08684298
# 7: Red a 1 0.08413131
# 8: Green a 1 0.03796001
# 9: Green b 3 0.07566126
# 10: Red b 2 0.09350268
# 11: Red b 2 0.04230800
# 12: Blue a 3 0.06935330
# 13: Blue b 3 0.03893384
# 14: Blue a 2 0.03166846
# 15: Green a 2 0.07369181
# 16: Green b 2 0.01972925
# 17: Green a 2 0.06921767
# 18: Green b 1 0.01184500
# 19: Red b 2 0.02389486
# 20: Blue b 2 0.01394867
P <- X[, prop.table(xtabs(~color + letter + number), c("color", "letter"))]
P <- data.table(P)
setnames(P, "N", "percentage")
# > P
# color letter number percentage
# 1: Blue a 1 0.0000000
# 2: Green a 1 0.5000000
# 3: Red a 1 0.5000000
# 4: Blue b 1 0.0000000
# 5: Green b 1 0.3333333
# 6: Red b 1 0.0000000
# 7: Blue a 2 0.6000000
# 8: Green a 2 0.5000000
# 9: Red a 2 0.0000000
# 10: Blue b 2 0.5000000
# 11: Green b 2 0.3333333
# 12: Red b 2 1.0000000
# 13: Blue a 3 0.4000000
# 14: Green a 3 0.0000000
# 15: Red a 3 0.5000000
# 16: Blue b 3 0.5000000
# 17: Green b 3 0.3333333
# 18: Red b 3 0.0000000
P[, sum(percentage), .(color, letter)]
# > P[, sum(percentage), .(color, letter)]
# color letter V1
# 1: Blue a 1
# 2: Green a 1
# 3: Red a 1
# 4: Blue b 1
# 5: Green b 1
# 6: Red b 1
Как видите, это невзвешенные пропорции. Я хотел бы взвесить их в соответствии с моей переменной weight
. В конечном счете, проценты все равно должны составлять 1. Я знаю, что может быть невозможно достичь таких результатов с помощью двух функций prop.table()
и xtabs()
, поэтому, если есть другое решение, это тоже хорошо.
xtabs
иprop.table
вместоdata.table
функциональности - person akrun   schedule 09.03.2021X %>% count(color, letter, number, wt = weight) %>% group_by(color, letter) %>% mutate(prop = n/sum(n), n1 = sum(prop))
- person akrun   schedule 09.03.2021X[, .(n = sum(weight)), .(color, letter, number)][, prop := n/sum(n), .(color, letter)][]
- person akrun   schedule 09.03.2021data.table
? Я бы предпочел избегатьdplyr
, если это возможно, поскольку я полагаюсь исключительно наdata.table
. - person mat   schedule 09.03.2021