0

I have a matrix which is made up of 4 columns (i.e. column 1, column 2, column 3 and column 4)

  V1 V2 V3 V4
1  1  1  1  1
2  1  1  1  1
3  1 -1 -1 -1
4  1 -1 -1 -1
5  2  1  1 -1
6  2  1  1 -1
7  2 -1 -1  1
8  2 -1 -1  1
9  3  1 -1  1
10 3  1 -1  1
11 3 -1  1 -1
12 3 -1  1 -1
13 4  1 -1 -1
14 4  1 -1 -1
15 4 -1  1  1
16 4 -1  1  1

My question is: I want to use this 4 columns to get a new matrix which has 15 columns. And these 15 columns are:

1, 2, 3, 4, 12, 13, 14, 23, 24, 34, 123, 124, 134, 234, 1234.

Here I use 12 to represent column 1 * column 2

So 1234 = column 1 * column 2 * column 3 * column 4.

Does anyone have some simple pieces of code to do this? Thanks for everyone's help.

4

2 回答 2

3

使用您拥有的三列,您可以执行以下操作:

 model.matrix(~ V1*V2*V3, data=x)

或这个:

 model.matrix(~ 0 + V1*V2*V3, data=x)

(编辑:最初有三列。解决方案以明显的方式扩展到 4 列)

这个想法很容易扩展到更多的列。

但是,如果您尝试这样做以拟合模型,那么您就是在浪费时间——无需直接计算它们。

于 2013-04-24T01:13:46.913 回答
1

尽管@Glen_b 的答案几乎可以肯定是可取的,但这是另一种尝试:

# make some sample data
dat <- data.frame(V1=1:3,V2=2:4,V3=3:5,V4=5:7)

# get all the possible combinations
comps <- Reduce(c,sapply(2:4,function(x) combn(1:4,x,simplify=FALSE)))
#str(comps)
#List of 11
# $ : int [1:2] 1 2
# $ : int [1:2] 1 3
# $ : int [1:2] 1 4
# $ : int [1:2] 2 3
# $ : int [1:2] 2 4
# $ : int [1:2] 3 4
# $ : int [1:3] 1 2 3
# $ : int [1:3] 1 2 4
# $ : int [1:3] 1 3 4
# $ : int [1:3] 2 3 4
# $ : int [1:4] 1 2 3 4

# multiply out the combinations    
data.frame(dat,sapply(comps,function(x) Reduce("*",dat[x]) ))

#  V1 V2 V3 V4 X1 X2 X3 X4 X5 X6 X7 X8  X9 X10 X11
#1  1  2  3  5  2  3  5  6 10 15  6 10  15  30  30
#2  2  3  4  6  6  8 12 12 18 24 24 36  48  72 144
#3  3  4  5  7 12 15 21 20 28 35 60 84 105 140 420

正如@mnel 在下面的评论中指出的那样,您还可以将一个函数传递给combn将应用于每个组合的函数,因此这将一步到位:

do.call(
        cbind,
          sapply(
          seq_along(dat),
          function(m) combn(m=m, x = dat, FUN = function(xx) Reduce('*',xx ))
                )
       )
于 2013-04-24T01:34:14.033 回答