2017-04-27 164 views
1
x1 x2 x3 x11 x12 x13 x22 x23 x33 
1 5 9 1 5 9 25 45 81 
2 6 10 4 12 20 36 60 100 
3 7 11 9 21 33 49 77 121 
4 8 12 16 32 48 64 96 144 

x1x2,和给出,我想建立一个矩阵或数据帧x11, x12, x13, x22, x23,和x33其是向量x1, x2的元素之积,和 。创建矩阵列的逐元素乘积

事实上,我想以此为更多的载体(例如x1 ~ x6)到高的顺序(第三或第四)。 有没有可以做到这一点的R命令?

+0

'M [T(山口(米))[lower.tri(吨(COL(M)),DIAG = TRUE)]] * M [,代表(1:NcoI位(M),NcoI位(M) :1)]((确保乘法的第一部分可以简化) – user2957945

+0

@ user2957945这是从我已发布的答案中得到灵感。即使'm [,rep(1:ncol(m),ncol(m):1)]'也完全一样。如果你有新的东西,那么继续! – 989

+0

@ 989;实际上它没有。这是一个不使用循环的尝试(即生成序列c(1,2,3,2,3,3)),但更一般地说,如果可以改进的话,建立在其他答案上是可以的 - 它是不是一个竞争(如果我有兴趣点我会把它放在答案部分) – user2957945

回答

2

我们可以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) 
0

你也不要这样相当的基础R矢量:

# Data 
m <- matrix(1:12,4,3) 

cl <- ncol(m) 
res <- cbind(m, m[,rep(seq(cl), cl:1)] * m[,unlist(Map(":", 1:cl, rep(cl,cl)))]) 

     # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] 
# [1,] 1 5 9 1 5 9 25 45 81 
# [2,] 2 6 10 4 12 20 36 60 100 
# [3,] 3 7 11 9 21 33 49 77 121 
# [4,] 4 8 12 16 32 48 64 96 144 

基本上,你首先选择您想拥有的列产品,然后一次完成。