[英]Calculate probability based on grouping variables in R
我需要根據一些分組變量計算響應的概率(df $ C)並將輸出寫回df。
以我的數據為例
A B C
1 1 1
2 1 0
3 1 1
1 2 0
2 2 1
3 2 1
所以最終,對於df $ A中的每個值,我最終都需要df $ C中出現值“ 1”的平均概率。 df $ A的值在分組變量df $ B中重復。 任何幫助,將不勝感激
您可以使用dplyr
。 在您的示例中,A和B列的每組中只有一個樣本,因此結果列與C列相同。
library(dplyr)
dat %>% group_by(B, A) %>%
mutate(res = mean(C==1))
# A B C res
# 1 1 1 1 1
# 2 2 1 0 0
# 3 3 1 1 1
# 4 1 2 0 0
# 5 2 2 1 1
# 6 3 2 1 1
數據
dat <- structure(list(A = c(1L, 2L, 3L, 1L, 2L, 3L), B = c(1L, 1L, 1L,
2L, 2L, 2L), C = c(1L, 0L, 1L, 0L, 1L, 1L), res = c(0.5, 0.5,
1, 0.5, 0.5, 1)), .Names = c("A", "B", "C", "res"), row.names = c(NA,
-6L), class = "data.frame")
由於我開始喜歡base R解決方案,因此這里是我的:
df1 <- split(df, list(df$A, df$B))
pr <- lapply(df1, function(x) mean(x$C == 1) )
df1 <- unsplit(df1, list(df$A, df$B))
df1$pr <- unlist(pr)
df1
A B C pr
1 1 1 1 1
2 2 1 0 0
3 3 1 1 1
4 1 2 0 0
5 2 2 1 1
6 3 2 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.