0

I am trying to add columns to several dataframes. I am trying to create a function that will add the columns and then I would want to use that function with lapply over a list of object. The function is currently just adding empty columns to the data frame. But, if I solve the problem below, I would like to add to it to automatically populate the new columns (and still keeping the initial name of the object). This is the code I have so far:

AAA_Metadata <- data.frame(AAA_Code=character(),AAA_REV4=character(),AAA_CONCEPT=character(),AAA_Unit=character(),AAA_Date=character(),AAA_Vintage=character())
add_empty_metadata <- function(x) {
temp_dataframe <- setNames(data.frame(matrix(ncol=length(AAA_Metadata),nrow=nrow(x))),as.list(colnames(AAA_Metadata))) 
x <- cbind(temp_dataframe,x)
}

However when I run this

a <- data.frame(matrix(ncol=6,nrow=100))
add_empty_metadata(a)

and look at the Global Environment object "a" still has 6 columns instead of 12. I understand that I am actually working on a copy of "a" within the function (based on the other topics I checked, e.g. Update data frame via function doesn't work). So I tried:

x <<- cbind(temp_dataframe,x)

and

x <- cbind(temp_dataframe,x)
assign('x',x, envir=.GlobalEnv)

But none of those work. I want to have the new a in the Global Environment for future reference and keep the name 'a' unchanged. Any idea what I am doing wrong here?

1 Answers1

0

Is this what you're looking for:

addCol <- function(x, newColNames){
    for(i in newColNames){
        x[,i] <- NA
    }
    return(x)
}
a <- data.frame(matrix(ncol=6,nrow=100));dim(a)
a <- addCol(a, newColNames = names(WIS_Metadata));dim(a)

Amazing source for this kind of stuff is Advanced R by Hadley Wickham with a website here.

R objects are immutable - they don't change - just get destroyed and rebuilt with the same name. a is never changed - it is used as an input to the function and unless the resulting object inside the function is reassigned via return, the version inside the function (this is a separate environment) is binned when the function is complete.

screechOwl
  • 27,310
  • 61
  • 158
  • 267