yenats
yenats

Reputation: 551

Tell R to use string stored in object as column name

I am trying the following:

a <- "b"
data.frame (a = c (1:3))

which returns (of course):

data.frame (a = c (1:3))
>   a
> 1 1
> 2 2
> 3 3

What I want is:

a <- "b"    
data.frame (foo (a) = c (1:3))
>   b
> 1 1
> 2 2
> 3 3

Is there a way to tell R to use the string ("b") stored in an object (a) as column name?

EDIT: I know that the title of my question is perhaps not very meaningful. Are there suggestions for improvement?

Upvotes: 2

Views: 921

Answers (2)

akrun
akrun

Reputation: 886938

One option is tibble and evaluate (!!) the object on the lhs of :=

tibble(!! a := 1:3)
# A tibble: 3 x 1
#      b
#  <int>
#1     1
#2     2
#3     3

We can also use set_names from dplyr

library(dplyr)
data.frame(1:3) %>%
     set_names(a)

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388797

You can also use setNames

setNames(data.frame(1:3), a)

#  b
#1 1
#2 2
#3 3

Or using matrix and adding dimnames

data.frame(matrix(1:3, ncol = 1, dimnames = list(NULL, a)))

Upvotes: 1

Related Questions