2

I wish to assign the same value to multiple variables in a data.frame. I have looked at multiple posts here that seem similar, but do not appear to address my specific problem.

Mass variable declaration and assignment in R?

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

Here is an example data.frame I would like to create:

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)

Thank you for any advice or assistance. I prefer a solution in base R. Sorry if the answer is obvious.

Community
  • 1
  • 1
Mark Miller
  • 12,483
  • 23
  • 78
  • 132

2 Answers2

7

How about (insert as many row.names as you want rows in the output 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

Or (column names won't be exactly right; thanks @Frank for simplifying my approach here)

data.frame(a = .641, c = -6.198, d = 35.052)[ , rep(1:3, each = 10)]
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
6

Do it all in one go:

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))
)
thelatemail
  • 91,185
  • 12
  • 128
  • 188