1

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 )  )
get(MEDIA[1])
   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

1
  • Why are you doing this? It is never necessary to assign objects to symbols programmatically like this. This looks like a misuse of assign. Commented Jul 21, 2021 at 16:40

1 Answer 1

1

It is probably better to put the created data frames in a list rather than having them floating around in workspace but to answer the question directly use setNames:

nm <- MEDIA[1]
assign(nm, setNames(data.frame(v1*2), nm))

This also works:

e <- .GlobalEnv
# e <- environment()   # use this if not in global env
nm <- MEDIA[1]
e[[nm]] <- data.frame(  v1*2 )
names(e[[nm]]) <- nm

To put them in a list:

L <- list()
nm <- MEDIA[1]
L[[nm]] <- setNames(data.frame( v1*2 ), nm) 

It may be possible to create the list all once using Map if there exists a formula for creating the data frames.

Sign up to request clarification or add additional context in comments.

Comments

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.