Home > Mobile >  Using lapply to set column names for a list of data frames?
Using lapply to set column names for a list of data frames?

Time:12-09

I'm pretty new to R but I'm trying to create a list of data frames and then give them all the same headers in a loop. The plan is to then fill the columns with data from a bunch of messy data files and then bind the small data frames all a single data frame. However, I'm stuck on assigning the column names. I did first try a for loop but saw other answers saying that was the newbie way to do it.

This is what I have right now but when I run it the columns don't update:

a <- data.frame(matrix(ncol=5, nrow=1))
b <- data.frame(matrix(ncol=5, nrow=1))
c <- data.frame(matrix(ncol=5, nrow=1))
d <- data.frame(matrix(ncol=5, nrow=1))

List <- list(a, b, c, d)
headers <- c("First Name","Last Name","Date","Zip Code", "blah")

lapply(List, setNames, nm = headers)

I think I'm missing something about how data frames are updated in R because I do get a print out of 4 empty data frames with the right column names. So the function is applying to something! But it's not updating my list and I'm failing to understand why.

Thank you!

CodePudding user response:

We can set column names using,

List = lapply(List, function(x) `colnames<-`(x, headers))

CodePudding user response:

It seems you want to update the original dataframes. In that case, your list MUST be named. ie check the code below.

List <- list(a = a, b = b, c = c, d = d)
list2env(lapply(List, setNames, nm = headers), globalenv())

Now if you call a you will note that it has been updated.

  • Related