【问题标题】:Keep column names after calling function combn调用函数combn后保留列名
【发布时间】:2015-01-22 14:04:36
【问题描述】:

在查看有关列名和组合函数 here 的另一篇文章后,请考虑相同的 data.frame。我们将所有 2 个可能的向量组合在一起:

foo <- data.frame(x=1:5,y=4:8,z=10:14, w=8:4)
all_comb <- combn(foo,2)

有没有办法在 combn 调用之后保留列名,所以在这种情况下,我们可以得到“x y”而不是“X1.5 X4.8”,如下所示?

comb_df <- data.frame(all_comb[1,1],all_comb[2,1])
print(comb_df)

  X1.5 X4.8
1    1    4
2    2    5
3    3    6
4    4    7
5    5    8

【问题讨论】:

标签: r combn


【解决方案1】:

我怀疑你真的想改用expand.grid()

试试这个:

head(expand.grid(foo))

  x y  z w
1 1 4 10 8
2 2 4 10 8
3 3 4 10 8
4 4 4 10 8
5 5 4 10 8
6 1 5 10 8

head(expand.grid(foo[, 1:2]))

  x y
1 1 4
2 2 4
3 3 4
4 4 4
5 5 4
6 1 5

【讨论】:

  • 感谢您的帮助安德烈。实际上,我的意思是使用 combn 函数来获取 4 个向量 (x,y,z,w) 的所有可能的 2 组合 (a,b)。我设法做到了,但列名没有保存在内存中,有没有可能做到这一点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 2017-10-14
  • 2015-06-28
  • 1970-01-01
  • 2013-11-06
相关资源
最近更新 更多