1

I have a list of dataframes in this form.

d1 <- data.frame(i = c("a","b","c"), var = 1:3, stringsAsFactors=FALSE)
d2 <- data.frame(i = c("b","c","d"), var = 5:8, stringsAsFactors=FALSE)
d3 <- data.frame(i = c("c","d","a"), var = 2:4, stringsAsFactors=FALSE)
dfList <- list(d1,d2,d3)

I want to change the var variables to var_d1, var_d2, var_d3 respectively to do a full-join later. How do I implement this? How do I retrive the name of the data frames and make them into strings?

Bunbury
  • 123
  • 5

5 Answers5

2

Start with naming the list

names(dfList) <- paste0('d', seq_along(dfList))

Once you do that you can use Map to rename columns :

Map(function(x, y) {names(x)[-1] <- paste(names(x)[-1], y, sep = "_");x}, 
                    dfList, names(dfList))

#$d1
#  i var_d1
#1 a      1
#2 b      2
#3 c      3

#$d2
#  i var_d2
#1 b      5
#2 c      6
#3 d      7

#$d3
#  i var_d3
#1 c      2
#2 d      3
#3 a      4

Or in tidyverse :

library(dplyr)
library(purrr)
imap(dfList, function(x, y) x %>% rename_with(~paste(., y, sep = "_"), -1))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0
dfList <- mget(paste0("d", 1:3))

mapply(function(df, name) {
  names(df)[names(df) == "var"] <- paste0("var_", name)
  df
}, dfList, names(dfList), SIMPLIFY = FALSE)

#> $d1
#>   i var_d1
#> 1 a      1
#> 2 b      2
#> 3 c      3
#> 
#> $d2
#>   i var_d2
#> 1 b      5
#> 2 c      6
#> 3 d      7
#> 
#> $d3
#>   i var_d3
#> 1 c      2
#> 2 d      3
#> 3 a      4
Aurèle
  • 12,545
  • 1
  • 31
  • 49
0

To changes the variables and then save them in a list of strings you can do something like this. (I think you made a mistake in d2 so I changed it)

d1 <- data.frame(i = c("a","b","c"), var = 1:3, stringsAsFactors=FALSE)
d2 <- data.frame(i = c("b","c","d"), var = 5:7, stringsAsFactors=FALSE)
d3 <- data.frame(i = c("c","d","a"), var = 2:4, stringsAsFactors=FALSE)
dfList <- list(d1,d2,d3)
column_names <- list()

for (i in 1:length(dfList)){
  colnames(dfList[[i]]) <- c("i",paste0("var_d",i))
  column_names[[i]] <- names(dfList[[i]])
} 

# they are stored here
column_names
[[1]]
[1] "i"      "var_d1"

[[2]]
[1] "i"      "var_d2"

[[3]]
[1] "i"      "var_d3"
flafont11
  • 137
  • 7
0

Maybe we can try the code below

> Map(function(k) setNames(dfList[[k]],c("i",paste0("var_d",k))),seq_along(dfList))
[[1]]
  i var_d1
1 a      1
2 b      2
3 c      3

[[2]]
  i var_d2
1 b      6
2 c      7
3 d      8

[[3]]
  i var_d3
1 c      2
2 d      3
3 a      4
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0

An approach quite similar to the ones proposed using Map, that uses lapply instead:

dfList <- lapply(
  1:length(dfList),
  function(x) setNames(dfList[[x]],
                       c('i', paste0('var_d', x))
                       )
  )
ira
  • 2,542
  • 2
  • 22
  • 36