问题
I want to append the dataframe-name to each of its columns in the following list of dataframes:
df1 <- tibble(V1=c(1, 1, 3, 1),
V2=c(2, 1, 2, 2),
V3=c(4, 1, 1, 2))
df2 <- tibble(V1=c(1, 1, 3, 1),
V2=c(2, 1, 2, 2),
V3=c(4, 1, 1, 2))
df <- list(df1, df2)
names(df) <- c("df1", "df2")
df
This is how I would like it to look:
$df1
# A tibble: 4 x 3
df1_V1 df1_V2 df1_V3
<dbl> <dbl> <dbl>
1 1 2 4
2 1 1 1
3 3 2 1
4 1 2 2
$df2
# A tibble: 4 x 3
df2_V1 df2_V2 df2_V3
<dbl> <dbl> <dbl>
1 1 2 4
2 1 1 1
3 3 2 1
4 1 2 2
I have tried:
appendDFnameToColumns <- function(df, prefix = "", sep = "") {
colnames(df) <- paste(prefix, colnames(df), sep = sep)
df
}
df <- map(df, appendDFnameToColumns,
prefix = names(df$.),
sep ="_")
Thanks in advance
回答1:
A tidyverse approach with purrrs imap :
library(dplyr)
library(purrr)
imap(df,~rename_with(.x, function(x) paste(.y, x, sep = '_')))
#$df1
# A tibble: 4 x 3
# df1_V1 df1_V2 df1_V3
# <dbl> <dbl> <dbl>
#1 1 2 4
#2 1 1 1
#3 3 2 1
#4 1 2 2
#$df2
# A tibble: 4 x 3
# df2_V1 df2_V2 df2_V3
# <dbl> <dbl> <dbl>
#1 1 2 4
#2 1 1 1
#3 3 2 1
#4 1 2 2
Or in base R you can use Map :
Map(function(x, y) setNames(x, paste(y, names(x), sep = '_')), df, names(df))
回答2:
With purrr:
library(tidyverse)
names(df) %>%
map(function(dtf) {get(dtf) %>% rename_with(~paste0(dtf,"_",.))})
[[1]]
# A tibble: 4 x 3
df1_V1 df1_V2 df1_V3
<dbl> <dbl> <dbl>
1 1 2 4
2 1 1 1
3 3 2 1
4 1 2 2
[[2]]
# A tibble: 4 x 3
df2_V1 df2_V2 df2_V3
<dbl> <dbl> <dbl>
1 1 2 4
2 1 1 1
3 3 2 1
4 1 2 2
回答3:
We can use rename with !!!
library(dplyr)
library(purrr)
library(stringr)
map2(df, names(df), ~ .x %>%
rename(!!! setNames(names(.), str_c(.y, names(.), sep="_"))))
-output
#$df1
# A tibble: 4 x 3
# df1_V1 df1_V2 df1_V3
# <dbl> <dbl> <dbl>
#1 1 2 4
#2 1 1 1
#3 3 2 1
#4 1 2 2
#$df2
# A tibble: 4 x 3
# df2_V1 df2_V2 df2_V3
# <dbl> <dbl> <dbl>
#1 1 2 4
#2 1 1 1
#3 3 2 1
#4 1 2 2
来源:https://stackoverflow.com/questions/64553949/r-append-dataframe-name-to-each-of-its-columns-within-a-list-of-dataframes