[英]Sum rows of each unique combination of variables in r
我想創建新變量,這些變量是 3 個原始變量的每個唯一組合的總和。
數據示例:
df1 <- data.frame(A=c(1,2,3,5.5,5), B=c(2,2,2,2,0.5), C=c(1.5,0,0,2.1,3), D=c(0.2,1,2,1,0.8), E=c(0.4,0.6,0.2,1.1,2))
A B C D E
1 1.0 2.0 1.5 0.2 0.4
2 2.0 2.0 0.0 1.0 0.6
3 3.0 2.0 0.0 2.0 0.2
4 5.5 2.0 2.1 1.0 1.1
5 5.0 0.5 3.0 0.8 2.0
我想使用 3 個變量的每個獨特組合創建新列。 例如,稱為“sum1”的新列組合了 A、B、C 列、“sum2”組合 A、B、D、“sum3”組合 A、B、E 等。
A B C D E sum1 sum2 sum3
1 1.0 2.0 1.5 0.2 0.4 3.5 3.2 3.4
2 2.0 2.0 0.0 1.0 0.6 4.0 5.0 4.6
3 3.0 2.0 0.0 2.0 0.2 5.0 7.0 5.2
4 5.5 2.0 2.1 1.0 1.1 9.6 8.5 8.6
5 5.0 0.5 3.0 0.8 2.0 8.5 6.3 7.5
從其他問題我發現這將選擇獨特的組合:
output <- combn(ncol(df1), 3, FUN = function(x) df1[x], simplify = FALSE)
這給了我 10 個(所有組合的數量)的列表,我可以查看使用 output[[1]]、output[[2]] 等選擇的每組變量,但是我如何對每個變量的行求和並將它們放入數據框中?
謝謝
我們可以做一個rowSums
並轉換為data.frame
,設置“輸出”的names
並使用原始數據集進行cbind
。
output <- as.data.frame(combn(ncol(df1), 3, FUN =function(x) rowSums(df1[x])))
names(output) <- paste0("sum_", combn(names(df1), 3, FUN = paste, collapse="_"))
cbind(df1, output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.