我有一个名为“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”中添加新生成的变量,而不是将它们保存在新变量中?
非常感谢你的帮助!