Column name df from a character string contained in a list

If I have a list of examples Names

Names <- list(A = c("one", "two", "three"),
              B = c("three", "four", "five"))

      

Is it possible to create a column header using one of the strings contained in the list? For example, the code below tries to create a named column One

by indexing Names[[1]][1]

, but clearly doesn't work.

data.frame(Names[[1]][1] = rep(5, 5))

      

Any suggestions would be appreciated. I tried to wrap as.character()

, but I am still looking for solutions. Real data is implemented in a loop and requires an index Names

. The desired result is shown below.

data.frame(One = rep(5, 5))

      

+3


source to share


1 answer


We can use setnames

to assign column names from a variable to a dataframe:

setNames(data.frame(rep(5, 5)), Names[[1]][1]) 

#  one
#1   5
#2   5
#3   5
#4   5
#5   5

      



which can definitely be used for multiple columns as well.

+1


source







All Articles