gpt4 book ai didi

r - 在 R 中导入和 rbind 多个具有通用名称的 csv 文件

转载 作者:行者123 更新时间:2023-12-01 11:45:45 24 4
gpt4 key购买 nike

我有多个 CSV 文件,它们的名称中有 4 个常用字符。
我想知道如何 rbind 具有相同公共(public)字符的文件。例如,“AM-25”在 3 个 csv 文件的名称中很常见,“BA-35”在另外 2 个文件的名称中很常见。

文件是这样的
AM-25.myfiles.2000.csv、AM-25.myfiles.2001.csv、AM-25.myfiles.2002.csv、BA-35.myfiles.2000.csv、
BA-35.myfiles.2001.csv,
我用它来读取所有文件:

files <- list.files(path=".", pattern="xyz+.csv", all.files = FALSE,full.names=TRUE )

最佳答案

你在寻找这样的东西吗?

do.call(rbind, lapply(list.files(path=".", pattern="AM-25"), read.table, header=TRUE, sep=","))

这将从包含字符“AM-25”的 csv 文件中读取的矩阵重新绑定(bind)在一起。 read.table 的参数可能会有所不同,具体取决于您的 csv 文件。

编辑

我希望这适用于您不知道目录中所有可能的文件名的五个字母前缀的情况:
##Get all different first five letter strings for all cvs files in directory "."                                                                                                                                                                                           
file.prefixes <- unique(sapply(list.files(path=".", pattern="*.csv"), substr, 1,5))

##Group all matching file names according to file.prefixes into a list
file.list <- lapply(file.prefixes, function(x)list.files(pattern=paste("^",x,".*.csv",sep=""), path="."))
names(file.list) <- file.prefixes ##just for convenience

##parse all csv files in file.list, create a list of lists containing all tables for each prefix
tables <- lapply(file.list, function(filenames)lapply(filenames, function(file)read.table(file, header=TRUE)))

##for each prefix, rbind the tables. Result is a list of length being length(file.prefixes)
## each containing a matrix with the combined data parsed from the files that match the prefix
joined.tables <- lapply(tables, function(t)do.call(rbind, t))

##Save tables to files
for (prefix in names(joined.tables))write.table(joined.tables[[prefix]], paste(prefix, ".csv", sep=""))

关于r - 在 R 中导入和 rbind 多个具有通用名称的 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15527720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com