Rename column of dataframes inside a list with its dataframe name

Viewed 1664

I have multiple dataframes/tibbles with the same exact structure, but different contents. Their name is the only way I can differentiate them. The objective is to merge them all together into one dataframe, with a factor column. The original dataframes have one column for each hour/measurement, so first I want to gather everything.

Imagine columns 5 to 11 of the mtcars df are my hour columns.

mt1 <- mtcars
mt2 <- mtcars
mt3 <- mtcars
mt4 <- mtcars

mtlist <- list(m1 = mt1,
               m2 = mt2,
               m3 = mt3,
               m4 = mt4)

require(tidyverse)

mtlist_tidy <- lapply(mtlist, function(x){
  df <- x %>%
    gather(exp, temp_name, 5:11)

  return(df)
})

Now I'm stuck. I need to rename the "temp_name" column in each of the dfs inside mtlist_tidy with the name of that df i.e. m1, m2, etc:

> head(mtlist_tidy$m1)
   mpg cyl disp  hp  exp temp_name
1 21.0   6  160 110 drat      3.90
2 21.0   6  160 110 drat      3.90
3 22.8   4  108  93 drat      3.85
4 21.4   6  258 110 drat      3.08
5 18.7   8  360 175 drat      3.15
6 18.1   6  225 105 drat      2.76

should become

> head(mtlist_tidy$m1)
   mpg cyl disp  hp  exp      m1
1 21.0   6  160 110 drat      3.90
2 21.0   6  160 110 drat      3.90
3 22.8   4  108  93 drat      3.85
4 21.4   6  258 110 drat      3.08
5 18.7   8  360 175 drat      3.15
6 18.1   6  225 105 drat      2.76

Then purrr::reduce(mtlist_tidy, full_join) would work, completing my task.

I guess there must a solution using only purrr and skipping lapply, but I'm not that familiar yet with this package.

4 Answers

I write a function to rename at specific columns

rename_fn <- function(df, col_ind, new_names) {
        names(df)[col_ind] <- new_names
        return(df)
}

Then simply use map2 from purrr

mtlist_tidy<-mtlist_tidy %>% map2(.,names(mtlist_tidy),
                            ~rename_fn(.x,col_ind = 6,new_names = .y))
Related