I have a list of dataframes. each dataframe has 1 column named "a" I want to rename column "a" of each dataframe pasting the name of the dataframe after the column name "a". Here is the example.
green <- data.frame(a=c(1,2,3,4,5))
> green
a
1 1
2 2
3 3
4 4
5 5
yellow <- data.frame(a=c(6,7,8,9,10))
black <- data.frame(a=c(11,12,13,14,15))
my_list <- list(green=green,
yellow=yellow,
black=black)
names(my_list)
[1] "green" "yellow" "black"
My desired results sould be something like:
> green
a_green
1 1
2 2
3 3
4 4
5 5
> yellow
a_yellow
1 6
2 7
3 8
4 9
5 10
and so on...
I was trying to do this with lapply but is there is something wrong I don't get...
my_list <- lapply(my_list, function(x)
colnames(x)=paste(colnames(x), names(x), sep = "_"))
CodePudding user response:
Here are couple of options -
- Using
tidyverse
-
library(dplyr)
library(purrr)
imap(my_list, ~.x %>% rename_with(function(x) paste(x, .y, sep = '_'), 1))
#$green
# a_green
#1 1
#2 2
#3 3
#4 4
#5 5
#$yellow
# a_yellow
#1 6
#2 7
#3 8
#4 9
#5 10
#$black
# a_black
#1 11
#2 12
#3 13
#4 14
#5 15
Or in base R -
Map(function(x, y) {
names(x)[1] <- paste(names(x)[1], y, sep = '_')
x
}, my_list, names(my_list))
You can simplify the process if you have only 1 column in each dataframe like in the example.
Map(setNames, my_list, paste('a', names(my_list), sep = '_'))
CodePudding user response:
You can use purrr::imap
library(tidyverse)
black <- tibble(a = 1:10)
yellow <- tibble(a = 11:21)
list("black" = black, "yellow" = yellow) %>%
imap(\(x, y){
x %>%
set_names(glue::glue("a_{y}"))
})
#> $black
#> # A tibble: 10 x 1
#> a_black
#> <int>
#> 1 1
#> 2 2
#> 3 3
#> 4 4
#> 5 5
#> 6 6
#> 7 7
#> 8 8
#> 9 9
#> 10 10
#>
#> $yellow
#> # A tibble: 11 x 1
#> a_yellow
#> <int>
#> 1 11
#> 2 12
#> 3 13
#> 4 14
#> 5 15
#> 6 16
#> 7 17
#> 8 18
#> 9 19
#> 10 20
#> 11 21