为多个变量分配相同的值

时间:2017-04-19 22:29:58

标签: r

我希望为data.frame中的多个变量分配相同的值。我在这里看了几篇看似相似的帖子,但似乎没有解决我的具体问题。

Mass variable declaration and assignment in R?

Assign multiple new variables on LHS in a single line in R

以下是我想要创建的示例data.frame

data = data.frame(
  a1 =  0.614, a2 =  0.614, a3 =  0.614, a4 =  0.614, a5  =  0.614,
  a6 =  0.614, a7 =  0.614, a8 =  0.614, a9 =  0.614, a10 =  0.614,
  c1 = -6.198, c2 = -6.198, c3 = -6.198, c4 = -6.198, c5  = -6.198,
  c6 = -6.198, c7 = -6.198, c8 = -6.198, c9 = -6.198, c10 = -6.198,
  d1 = 35.952, d2 = 35.952, d3 = 35.952, d4 = 35.952, d5  = 35.952,
  d6 = 35.952, d7 = 35.952, d8 = 35.952, d9 = 35.952, d10 = 35.952)

感谢您提供任何建议或帮助。我更喜欢基础R中的解决方案。对不起,如果答案很明显。

2 个答案:

答案 0 :(得分:7)

如何(在输出row.names中插入尽可能多的data.frame行):

data = data.frame(row.names = '1')
data[paste0('a', 1:10)] = .614
data[paste0('c', 1:10)] = -6.198
data[paste0('d', 1:10)] = 35.952

或(列名称不完全正确;感谢@Frank简化我的方法)

data.frame(a = .641, c = -6.198, d = 35.052)[ , rep(1:3, each = 10)]

答案 1 :(得分:6)

一气呵成:

n <- 10
setNames(
  data.frame(rep(list(0.641,-6.198,35.952), each=n)),
  paste0(rep(c("a","c","d"),each=n), seq_len(n))
)