1

我有一个名为“dat”的数据框,其中包含 5 个数值变量(var1、var2、var3、var4、var5),每个变量有 20 个观察值。

structure(list(var_1 = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 
13, 14, 15, 16, 17, 18, 19, 20), var_2 = c(7, 8, 9, 10, 11, 12, 
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26), var_3 = c(4, 
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 
22, 23), var_4 = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 
15, 16, 17, 18, 19, 20, 21)), row.names = c(NA, -20L), class = c("tbl_df", 
"tbl", "data.frame"))

我正在使用此代码创建并保存到一个新的数据框(名为“组合”)中,这 5 个变量的所有可能组合对与组合在一起的 2 个变量的平均值:

combined <- combn(dat, 2, FUN = rowMeans)

这是结果:

structure(c(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 
18, 19, 20, 21, 22, 23, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 
10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5, 19.5, 20.5, 
21.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 
12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5, 19.5, 20.5, 5.5, 6.5, 
7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 
18.5, 19.5, 20.5, 21.5, 22.5, 23.5, 24.5, 4.5, 5.5, 6.5, 7.5, 
8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5, 
19.5, 20.5, 21.5, 22.5, 23.5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 
13, 14, 15, 16, 17, 18, 19, 20, 21, 22), .Dim = c(20L, 6L))

1)代码工作正常,但问题是数据框中“组合”的新生成变量被命名为V1,V2,V3,V4......。而且我无法理解变量组合来自每个新变量。我希望将新生成的变量命名为“var1var2”、“var1var3”等等……有没有办法获得这个?

2)另外,有没有办法将combn函数仅应用于某些列而不应用于数据框“dat”中存在的所有变量?

3) 如何在原始数据框“dat”中添加新生成的变量,而不是将它们保存在新变量中?

非常感谢你的帮助!

4

1 回答 1

2

这可以通过combn使用列名重做语句来完成

set.seed(99)
dat <- data.frame(var1 = sample(20),           #some sample data
                  var2 = sample(20),           #I did this before you added your data above!
                  var3 = sample(20),
                  var4 = sample(20),
                  var5 = sample(20))

dat
   var1 var2 var3 var4 var5
1    12    5   18   19   12
2     3    2   10    6   13
3    13   15   14   13    1
4    17   11   16   18   10
5     9   13    8    8    7
6    15    6   20   17    3  
...

combined <- combn(dat, 2, FUN = rowMeans)      #your statement using cols of dat

colnames(combined) <- combn(names(dat), 2, paste0, collapse="") #same using colnames

combined

      var1var2 var1var3 var1var4 var1var5 var2var3 var2var4 var2var5 var3var4 var3var5 var4var5
 [1,]      8.5     15.0     15.5     12.0     11.5     12.0      8.5     18.5     15.0     15.5
 [2,]      2.5      6.5      4.5      8.0      6.0      4.0      7.5      8.0     11.5      9.5
 [3,]     14.0     13.5     13.0      7.0     14.5     14.0      8.0     13.5      7.5      7.0
 [4,]     14.0     16.5     17.5     13.5     13.5     14.5     10.5     17.0     13.0     14.0
 [5,]     11.0      8.5      8.5      8.0     10.5     10.5     10.0      8.0      7.5      7.5
 [6,]     10.5     17.5     16.0      9.0     13.0     11.5      4.5     18.5     11.5     10.0
 ...

要回答您的其他观点,您可以限制使用的列,例如dat[,c(2,3,6)]comb语句中(使用第 2、3 和 6 列)。您可以将它们添加回相同的数据框dat <- cbind(dat, combined)

于 2019-11-19T21:27:39.427 回答