0

To create a data.frame or a list I can write

data.frame(yo=1:2, wesh=3:4)

  yo wesh
1  1    3
2  2    4

list(yo=1:2, wesh=3:4)

$yo
[1] 1 2

$wesh
[1] 3 4

But if I write

i <- "yo"
data.frame(i=1:2, wesh=3:4)

   i wesh
1  1    3
2  2    4

list(i=1:2, wesh=3:4)
$i
[1] 1 2

$wesh
[1] 3 4

The i doesn't update to "yo" in the output. How to make it possible?

Sotos
  • 51,121
  • 6
  • 32
  • 66
user3631369
  • 329
  • 1
  • 12

1 Answers1

2

The reason is because It is not evaluated when you define it as the name of the variable in data.frame(). Try data.frame(i = i, wesh = 3:4) to see the difference. However, a workaround can be to use setNames, i.e.

setNames(data.frame(1:2, 3:4), c(i, 'wesh'))

#same for lists
#setNames(list(1:2, 3:4), c(i, 'wesh'))

which gives,

   yo wesh
1  1    3
2  2    4
Sotos
  • 51,121
  • 6
  • 32
  • 66