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?

1
  • 1
    x <- data.frame(i=1:2, wesh=3:4) i <- "yo" library(data.table) setnames(x, old=c("i"), new=c("yo")) Commented Apr 19, 2018 at 10:16

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.