0

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

3 Answers 3

3

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

Comments

2

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

Comments

1

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

Comments

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.