问题描述
我一直想知道是否有人知道在 R 中创建加载文件/数据库的循环的方法.假设我有一些这样的文件:data1.csv、data2.csv、...、data100.csv.
I have been wondering if anybody knows a way to create a loop that loads files/databases in R.Say i have some files like that: data1.csv, data2.csv,..., data100.csv.
在某些编程语言中,您可以执行类似 data +{ x }+ .csv 的操作,系统会将其识别为 datax.csv,然后您可以应用循环.
In some programming languages you one can do something like this data +{ x }+ .csv the system recognizes it like datax.csv, and then you can apply the loop.
有什么想法吗?
推荐答案
Sys.glob()
是另一种可能性 - 它的唯一目的是通配符或通配符扩展.
Sys.glob()
is another possibility - it's sole purpose is globbing or wildcard expansion.
dataFiles <- lapply(Sys.glob("data*.csv"), read.csv)
这会将 data[x].csv
形式的所有文件读入列表 dataFiles
,其中 [x]
是什么或任何东西.
That will read all the files of the form data[x].csv
into list dataFiles
, where [x]
is nothing or anything.
[请注意,这与@Joshua 的回答中的模式不同.在那里,list.files()
采用正则表达式,而 Sys.glob()
仅使用标准通配符;可以使用哪些通配符取决于系统,可以在帮助页面 ?Sys.glob
上找到可以使用的详细信息.]
[Note this is a different pattern to that in @Joshua's Answer. There, list.files()
takes a regular expression, whereas Sys.glob()
just uses standard wildcards; which wildcards can be used is system dependent, details can be used can be found on the help page ?Sys.glob
.]
这篇关于在 R 中循环以读取许多文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!