0

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.

1
  • 1
    Are you wedded to eval/parse? How about just: setNames(data.frame(sapply(nameslist, \(x) 1:5)), nameslist) Commented Apr 24, 2022 at 1:21

1 Answer 1

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

4 Comments

Thanks for this approach. However is this versatile?, what if the values in A and C are different (I only used 1:5 as an example). Can you give me an example code that would also work similarly for if it is, df <- data.frame( A = c(1,3,6,9,10) , C= c(2,3,5,6,10) ), I've just edited the above question accordingly
Sure, but the values have to come from somewhere. Are those values in a list too? I'm sorry, its not clear what you want. If you had the original values in a list, you could just directly convert to data.frame.
can you use those values as they are specified above, c(1,3,6,9,10) and c(2,3,5,6,10). Or create a list for each call them List_A<- c(1,3,6,9,10) and List_C<-c(2,3,5,6,10), and reference them in.. I've edited question again to match
If you have them in those vectors, just make them into a list, wrap in data.frame, and wrap in setNames - see my edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.