Elixterra
Elixterra

Reputation: 281

Renaming columns after dataframe names

I am still a newbee in R. I have 24 csv files. I would like to import them (at once without having to call them one by one) as dataframes with shorter dataframe names and, for each dataframe replace some colnames based on the name of the dataframe (or the .csv file name). Here follows an example with 3 dataframes.


df_ABX <- read.table(text = 'Name   col1    col2    col3    col4
                             name1  10  20  30  40
                             name2   5  10  15  20
                             name13 17  16  15  14', 
                 header = TRUE)  

df_BAX <- read.table(text = 'Name   col1    col2    col3    col4
                             name1  11  21  31  41
                             name2   4   9   8  19
                             name13 10  10  15  15', 
                 header = TRUE)

df_XAB <- read.table(text = 'Name   col1    col2    col3    col4
                             name1   9  19  29  28
                             name2  15  15  55  25
                             name13 18  10  11  12', 
                 header = TRUE)

In the previous example, I would like the csv file named myverylongtitle_df_ABX.csv, myverylongtitle_df_ABX.csv and myverylongtitle_df_ABX.csv to be imported as dataframe with following names: df_ABX, df_ABX, df_ABX. Then, I would like col1, col2, col3 to be renamed A, B or X depending on the position of these letters in the dataframe name. For example: col2 should be renamed after the letter in position 2 in dataframe names, that is: B if dataframe is df_ABX, A if dataframe is df_BAX, and Z if dataframe is df_XAB. Same should apply for col1 (position 1) and col3 (position 3).

Upvotes: 1

Views: 247

Answers (2)

akrun
akrun

Reputation: 887971

We can use rename_at after placing it in a list

library(tidyverse)
lst(df_ABX, df_BAX, df_XAB) %>% 
      imap(~  {
      nm1 <- str_remove(.y, 'df_') %>%
               strsplit("") %>% 
               unlist
   .x %>%
         rename_at(2:4, ~ nm1)})
#$df_ABX
#    Name  A  B  X col4
#1  name1 10 20 30   40
#2  name2  5 10 15   20
#3 name13 17 16 15   14

#$df_BAX
#    Name  B  A  X col4
#1  name1 11 21 31   41
#2  name2  4  9  8   19
#3 name13 10 10 15   15

#$df_XAB
#    Name  X  A  B col4
#1  name1  9 19 29   28
#2  name2 15 15 55   25
#3 name13 18 10 11   12

Upvotes: 2

Julian_Hn
Julian_Hn

Reputation: 2141

If you're fine with a list, this is a way to do it:

files <- c("myverylongtitle_df_ABX.csv","myverylongtitle_df_BAX.csv","myverylongtitle_df_BXA.csv")

lapply(files,function(file)
  {
  df <- read.table(file)
  spl <- strsplit(file,"_")[[1]]
  name <- sub("\\.csv","",spl[length(spl)])
  names(df)[2:4] <- strsplit(name,"")[[1]])
  return(paste0("df_",name)=df)
})

Upvotes: 1

Related Questions