spazznolo
spazznolo

Reputation: 769

How to Add Dataframe name to Columns from Multiple Dataframes

The goal is to rename a list of dataframes columns, but while adding the dataframe name to the new column name.

ex: from x to a_x and b_x.

Why? Because I plan to later merge the sets and would like clean ids for the columns.

a = data.frame(x = c(1,2))
b = data.frame(x = c(3,4))

frameList = list(a = a, b = b)

newName = c(*frameName+'_'+'x')
names = lapply(names, setNames, nm = newName)
list2env(names,.GlobalEnv)

Upvotes: 0

Views: 202

Answers (2)

akrun
akrun

Reputation: 887158

Or another option is Map

Map(function(x, y) setNames(x, paste(y, names(x),  sep="_")), frameList, names(frameList))
#$a   
#   a_x a_y
#1   1   1
#2   2   2

#$b
#  b_x b_y
#1   3   1
#2   4   2

Or with tidyverse

library(purrr)
library(dplyr)
f1 <- function(x, y) paste(y, x, sep="_")
map2(frameList, names(frameList), ~ .x %>% 
                                      rename_all(f1, .y))

If we need it in the reverse order, this is more simple

map2(frameList, names(frameList), ~ .x %>%
                            rename_all(paste, sep="_", .y))

Upvotes: 1

jazzurro
jazzurro

Reputation: 23574

Here is one way for you. I looped through each data frame in frameList using the length of frameList. For column names in each data frame, I took the name of a data frame (i.e., names(frameList)) and past it to column names in the data frame.

a = data.frame(x = c(1,2), y = 1:2)
b = data.frame(x = c(3,4), y = 1:2)

frameList = list(a = a, b = b)

lapply(1:length(names(frameList)), function(x) {

       names(frameList[[x]]) <- paste(names(frameList)[x], names(frameList[[x]]), sep = "_")

       return(frameList[[x]])

})

[[1]]
  a_x a_y
1   1   1
2   2   2

[[2]]
  b_x b_y
1   3   1
2   4   2

Upvotes: 2

Related Questions