创建向量的所有 2 路组合的方法是使用combn:
> combn(x, 2)
[,1] [,2] [,3] [,4]
[1,] "Sepal.Length" "Sepal.Length" "Sepal.Length" "Sepal.Width"
[2,] "Sepal.Width" "Petal.Length" "Petal.Width" "Petal.Length"
[,5] [,6]
[1,] "Sepal.Width" "Petal.Length"
[2,] "Petal.Width" "Petal.Width"
然后您可以遍历该字符矩阵的列:
comb.names <- combn(x, 2)
for ( i in 2:ncol(comb.names) ){ test <- cbind(test,
iris[[ comb.names[1,i] ]]*iris[[ comb.names[2,i] ]])
names(test)[i] <- paste( substr(comb.names[1,i],1,7),
substr( comb.names[2,i],1,7),sep="_")}
str(test)
#--------------------
'data.frame': 150 obs. of 6 variables:
$ SepL.SepW : num 17.8 14.7 15 14.3 18 ...
$ Sepal.L_Petal.L: num 7.14 6.86 6.11 6.9 7 9.18 6.44 7.5 6.16 7.35 ...
$ Sepal.L_Petal.W: num 1.02 0.98 0.94 0.92 1 2.16 1.38 1 0.88 0.49 ...
$ Sepal.W_Petal.L: num 4.9 4.2 4.16 4.65 5.04 6.63 4.76 5.1 4.06 4.65 ...
$ Sepal.W_Petal.W: num 0.7 0.6 0.64 0.62 0.72 1.56 1.02 0.68 0.58 0.31 ...
$ Petal.L_Petal.W: num 0.28 0.28 0.26 0.3 0.28 0.68 0.42 0.3 0.28 0.15 ...
#------------------
真正快速的方法...假设您正在考虑回归问题是使用 R 公式评估:
lm(as.numeric(Species) ~ (.)^2, data=iris)
Call:
lm(formula = as.numeric(Species) ~ (.)^2, data = iris)
Coefficients:
(Intercept) Sepal.Length
4.425390 -0.792828
Sepal.Width Petal.Length
-1.119006 0.228466
Petal.Width Sepal.Length:Sepal.Width
1.378179 0.240113
Sepal.Length:Petal.Length Sepal.Length:Petal.Width
-0.004753 -0.050226
Sepal.Width:Petal.Length Sepal.Width:Petal.Width
-0.017482 -0.356884
Petal.Length:Petal.Width
0.135710