Search code examples
rdplyrquantmodrbind

Rename Columns of all Data Frames in Environment R


Looking for a way to rename columns of all data frames in my R environment.

I have 3 dataframes, which we can call a, b, and c with the respective column names:

# a
AMZN.Open AMZN.Close AMZN.Volume

#b
AAPL.Open AAPL.Close AAPL.Volume

#c
MSFT.Open MSFT.Close MSFT.Volume

I want to rename the columns of all the data frames to "Open", "Close", and "Volume" so they can be binded together (ideally in one call, and a solution robust enough to handle many more than just 3 environment objects).

Is there a way this can be applied?


Solution

  • Here is one way with rename_with and a user-defined function.

    # Create example data frames
    dat_a <- data.frame(AMZN.Open = NA, AMZN.Close = NA, AMZN.Volume = NA)
    dat_b <- data.frame(AAPL.Open = NA, AAPL.Close = NA, AAPL.Volume = NA)
    dat_c <- data.frame(MSFT.Open = NA, MSFT.Close = NA, MSFT.Volume = NA)
    
    dat_list <- list(dat_a, dat_b, dat_c)
    
    # Load the package
    library(tidyverse)
    
    # Define a function to rename the column names
    col_fun <- function(x){
      y <- str_remove(x, pattern = ".*\\.")
      return(y)
    }
    
    # Apply the function with rename_with
    dat_list2 <- map(dat_list, ~rename_with(.x, .fn = col_fun))
    
    # Print the results
    dat_list2
    # [[1]]
    # Open Close Volume
    # 1   NA    NA     NA
    # 
    # [[2]]
    # Open Close Volume
    # 1   NA    NA     NA
    # 
    # [[3]]
    # Open Close Volume
    # 1   NA    NA     NA
    

    Update

    # Load the package
    library(tidyverse)
    
    # Extract the stock ticker
    stock_ticker <- function(x){
      y <- str_extract(x, pattern = "^.*(?=\\.)")
      
      y <- unique(y)
      
      if (length(y) > 1){
        stop("More than one stock ticker")
      }
      
      return(y)
    }
    
    # Define a function to rename the column names
    col_fun <- function(x){
    
      y <- str_remove(x, pattern = ".*\\.")
      
      return(y)
    }
    
    
    # Apply the function with rename_with and apply the sotck_ticker function
    dat_list2 <- map(dat_list, function(x){
      col <- names(x)
      
      ticker <- stock_ticker(col)
      
      x2 <- x %>%
        rename_with(.fn = col_fun) %>%
        mutate(`Stock Ticker` = ticker)
      return(x2)
    })