3

If I have the example list Names

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

Is it then possible to create a column heading using one of the strings contained in the list? For example, the code below is trying to create a column named One by indexing Names[[1]][1] but clearly does not work.

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

Any suggestions would be appreciated. I tried to wrap with as.character() but am still searching for solutions. The real data is being implemented within a loop and requires on the Names index. The desired out come is shown below.

data.frame(One = rep(5, 5))
B. Davis
  • 3,391
  • 5
  • 42
  • 78
  • 1
    Maybe with this. `setNames(data.frame(rep(5, 5)), Names[[1]][1])` ?? – Ronak Shah Jul 03 '17 at 03:29
  • Seems to work well and can be expanded for multiple new columns. nice. post as an answer...? – B. Davis Jul 03 '17 at 03:40
  • At first, I thought this is a duplicate but couldn't find an appropriate question, hence answering it. – Ronak Shah Jul 03 '17 at 03:45
  • Possible duplicate of https://stackoverflow.com/questions/30083351/variable-as-a-column-name-in-data-frame or https://stackoverflow.com/questions/7531868/how-to-rename-a-single-column-in-a-data-frame – akrun Jul 03 '17 at 04:05

1 Answers1

1

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 definitely can be used for multiple columns as well.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213