0

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)

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

@chachimouchacha Pleasure to help you.
1

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))

8 Comments

Much simpler. :)
@jazzurro thanks, I was looking for a tidyverse option, but it seems to be having some problem with rename_at
They even have rename_at? I do not see that in the CRAN manual version 0.7.4. Did you try to use it in Map()?
@jazzurro Yes, they do have a whole army of functions. I used it in map2. updated the post
I know up to filter_at/all/if. Now I have more things to catch up. I need to learn purrr too. I've been lately more into learning analytical packages for my work, and I cannot learn all at the same time. Is purrr stable now?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.