gpt4 book ai didi

从多个文件夹读取所有脚本和数据文件

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

我有两个文件夹,folder1folder2,每个文件夹包含大约 200 个文件,这些文件是 *rda*R.我想读取这两个目录中的所有文件和数据集。我怎样才能做到这一点?

路径:

folder1:  C:\folder1
folder2: C:\folder2

我的试用

setwd("C:/folder1")
myls <- ls() # do work as this will only list that are already loaded in the system
setwd("C:/folder2")
myls2 <- ls()
myls # do work as this will only list that are already loaded in the system

我知道这是一个简单的问题,但我没有任何答案。

最佳答案

由于.rda需要load.R需要source,我会这样做:

file.sources = list.files(pattern="*.R")
data.sources = list.files(pattern="*.rda")
sapply(data.sources,load,.GlobalEnv)
sapply(file.sources,source,.GlobalEnv)

更新为一次读取多个文件夹

file.sources = list.files(c("C:/folder1", "C:/folder2"), 
pattern="*.R$", full.names=TRUE,
ignore.case=TRUE)
data.sources = list.files(c("C:/folder1", "C:/folder2"),
pattern="*.rda$", full.names=TRUE,
ignore.case=TRUE)
sapply(data.sources,load,.GlobalEnv)
sapply(file.sources,source,.GlobalEnv)

还要注意在搜索模式末尾使用 $,以确保它仅匹配行末尾的 .R,以及使用 ignore.case 以防某些文件被命名为 script.r

关于从多个文件夹读取所有脚本和数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291520/

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