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