将df的每个列重命名为其文件名的一部分 - R

3
我有一些文件,它们的命名规则相同,并且所有列名也相同:
ABC_file_name_25
ABC_file_name_50
ABC_file_name_100

我希望每个 df 的列名都能代表它们来自哪个文件。目前所有的 df 都有相同的列名:
col1    col2     col3

我希望它们是:

df1

col1_ABC_25    col2_ABC_25    col3_ABC_25

df2

col1_ABC_50    col2_ABC_50    col3_ABC_50

df3

col1_ABC_100    col2_ABC_100    col3_ABC_100

到目前为止,我已经有了这个,但我不确定如何将名称应用于列:
library(tools)

# Working Directory
setwd("C:/.../Files")

# Get a list of files to read in
temp = list.files(pattern="*.csv")
# Remove .csv
file_name = file_path_sans_ext(temp)
# Get the start of filename prefix 
prefix = sub("_.*", "", file_name[1:1])
# Get the suffix number
suffix = sub(".*_", "", file_name)

# Name each df by its filename
for (i in 1:length(temp)) assign(file_path_sans_ext(temp[i]), read.csv(temp[i]))
# Place all df into a list using their prefix
list <- lapply(ls(pattern=prefix), function(x) get(x))
1个回答

1
这将会把每个文件加载为一个数据框,根据需要更改列名,并将它们收集到一个列表中。
filenames <- list.files(pattern="*.csv")

all_files <- lapply(filenames, function(x) {
    file <- read.csv(x)
    # Get the start of filename prefix 
    prefix = sub("_.*", "", x)
    # Get the suffix number
    suffix = sub(".*_", "", x)

    colnames(file) <- paste(colnames(file), prefix, suffix, sep='_')
    return(file)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接