Using name from list, for the name of a newly create a dataframe (using assign), but want to also use that name for the variable within

I'm creating a dataframe, naming the df with a name from a list using "assign". But I also want the column name /variable to have that same name. Here is example data

MEDIA <- c("TV", "Radio", "Cinema")
v1 <- 1:10
assign( MEDIA[1] , data.frame(  v1*2 )  )
1       2
2       4
3       6
4       8
5      10
6      12
7      14
8      16
9      18
10     20

I created a df with name TV, but I want the variable within to also be named TV but using MEDIA[1] in the code, as I'm doing this in a "for loop".

I tried looking at it from this angle to create it within the assign, which works if you type the actual "TV" into it, but doesn't read MEDIA[1].

assign( MEDIA[1] , data.frame( TV = v1*2 )) # This works
assign( MEDIA[1] , data.frame( MEDIA[1] = v1*2 )) # This doesn't work

I've also tried to name the variable after creating the dataframe

names( TV ) <- MEDIA[1] # This works
names(MEDIA[1] ) <- MEDIA[1] # This doesn't work

Again using the "TV" works, but not when I use MEDIA[1].

Maybe there also a way to name the column/variable the same as the dataframe name?
If it helps there's only ever one single variable at a time.

I hope all that made sense. Any help is greatly appreciated. Thanks

Read more here:

Content Attribution

This content was originally published by H.Cheung at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: