Search code examples
rassignment-operator

Use assign() function to assign column names into an empty data frame in R


I have an empty data frame, whose name was created by assign() function.

x <- "Sale"
y <- "2015"
col_names <- c("Q1","Q2","Q3")
assign(paste0(x,y), data.frame(matrix(nrow = 0, ncol = length(col_names))))

content of x,y and col_names was dynamic. How should I assign col_names to the data frame: "paste0(x,y)" ?

assign(colnames(paste0(x,y)),col_names)

I've tried this , but in vain. Is there any way to solve this problem? Thanks a lot!


Solution

  • The difficulty you're having (how do I refer in later code to an object created with a dynamically generated name) is precisely why assign is a bad idea. Your problem is actually caused by your desire to use assign.

    Put the data frame in a list with a non-dynamic variable name, and set the name of that element of the list using the "dynamic" elements:

    a <- list(setNames(data.frame(matrix(nrow = 0, ncol = length(col_names))),col_names))
    names(a) <- paste0(x,y)
    
    > a
    $Sale2015
    [1] Q1 Q2 Q3
    <0 rows> (or 0-length row.names)