specify a variable name in a dataframe, using an element from list

I’m trying to use an element from a list to specify a variable name in a dataframe.
I know I can create a dataframe like this, creating variable A and C

list_A <- c(1,3,6,9,10)
List_C <- c(2,3,5,6,10)
df <- data.frame( A = list_A , C = List_C ) 
> df
   A  C
1  1  2
2  3  3
3  6  5
4  9  6
5 10 10

However, I’d like to specify the variable names from elements from a list, in this manner

nameslist <- c("A","B","C")
df <- data.frame( eval(parse(text=nameslist[1])) = List_A , eval(parse(text=nameslist[3])) = List_C ) 

I tried this, but cant get this code to run. Is there a way to adjust the "eval/parse" bit to make this work? Many thanks in advance.

>Solution :

nameslist <- c("A","B","C")
setNames(data.frame(sapply(nameslist[c(1,3)], \(x) 1:5)), nameslist[c(1,3)])

Or, if you simply had a set of values_for_A and a set of values_for_C, you could do something like this:

setNames(data.frame(list(values_for_A, values_for_C)), nameslist[c(1,3)])

Leave a Reply