我們可以expand.grid
做相結合,找到列的所有組合1:3,然後依次通過行,子集的數據集,並得到這些
nm1 <- names(df1)[1:3]
apply(expand.grid(nm1, nm1), 1, FUN = function(x) Reduce(`*`, df1[x]))
的*
以上輸出給所有的組合,但如果假設我們要刪除是鏡像
#expand the names to two columns with each combination
d1 <- expand.grid(nm1, nm1)
#remove the rows that are duplicates
d2 <- d1[!duplicated(t(apply(d1, 1, sort))),]
#apply the function and change the column names
d3 <- apply(d2, 1, FUN = function(x) Reduce(`*`, df1[x]))
colnames(d3) <- do.call(paste0, d2)
及其組合,如果需要cbind
與所述第一3列
cbind(df1[1:3], d3)
另一種選擇是combn
d1 <- as.data.frame(combn(nm1, 2, FUN = function(x) Reduce(`*`, df1[x])))
nm2 <- combn(nm1, 2, FUN = paste, collapse="")
names(d1) <- nm2
d2 <- setNames(as.data.frame(df1[1:3]^2), paste0(nm1, nm1))
cbind(df1[1:3], d1, d2)
'M [T(山口(米))[lower.tri(噸(COL(M)),DIAG = TRUE)]] * M [,代表(1:NcoI位(M),NcoI位(M) :1)]((確保乘法的第一部分可以簡化) – user2957945
@ user2957945這是從我已發佈的答案中得到靈感。即使'm [,rep(1:ncol(m),ncol(m):1)]'也完全一樣。如果你有新的東西,那麼繼續! – 989
@ 989;實際上它沒有。這是一個不使用循環的嘗試(即生成序列c(1,2,3,2,3,3)),但更一般地說,如果可以改進的話,建立在其他答案上是可以的 - 它是不是一個競爭(如果我有興趣點我會把它放在答案部分) – user2957945