Applying a function to a list of data frames removes the data

Viewed 38

Here's some mock data that resembles the data I'm working with:

df1 <- data.frame(Date.Time..GMT.04.00 = c(1, 2, 3, 4, 5),
                  var1 = c('a', 'b', 'c', 'd', 'e'),
                  var2 = c(1, 1, 0, 0, 1))
df2 <- data.frame(Date.Time..GMT.05.00 = c(1, 2, 3, 4, 5),
                  var1 = c('a', 'b', 'c', 'd', 'e'),
                  var2 = c(1, 1, 0, 0, 1))

I put the data frames into a list so that I'll be able to apply a function to each of the data frames:

df.list <- list(df1, df2)

Here's the function that I source in:

change_date_name <- function(df){
  colnames(df) <- sub("^Date.Time..GMT.0\\d.00", "Date_Time", colnames(df))
}

Now, I apply the function to the data frame list:

df.list <- lapply(df.list, change_date_name)

When I apply the function to the list, it successfully changes the name in each data frame, but it creates a new column in each data frame called "V1", which is a character column that contains the previous columns' names, causing the data to disappear. How can I apply the function to change the column name in each data frame without losing the data?

Using R version 3.5.1, Mac OS X 10.13.6

1 Answers

You need to return the data frame, otherwise by default functions in R will return the output from the last line you called, which is colnames():

change_date_name <- function(df){
      colnames(df) <- sub("^Date.Time..GMT.0\\d.00", "Date_Time",colnames(df))
      return(df)
    }

 lapply(df.list, change_date_name)
[[1]]
  Date_Time var1 var2
1         1    a    1
2         2    b    1
3         3    c    0
4         4    d    0
5         5    e    1

[[2]]
  Date_Time var1 var2
1         1    a    1
2         2    b    1
3         3    c    0
4         4    d    0
5         5    e    1
Related