重命名环境R中所有数据帧的列



正在寻找一种方法来重命名R环境中所有数据帧的列。

我有3个数据帧,我们可以用各自的列名来调用a、b和c:

# a
AMZN.Open AMZN.Close AMZN.Volume
#b
AAPL.Open AAPL.Close AAPL.Volume
#c
MSFT.Open MSFT.Close MSFT.Volume

我想将所有数据帧的列重命名为"0";打开"关闭";,以及";"体积";因此,它们可以绑定在一起(理想情况下是在一个调用中,并且解决方案足够健壮,可以处理3个以上的环境对象(。

有什么方法可以应用吗?

以下是使用rename_with和用户定义函数的一种方法。

# 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

更新

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

最新更新