将多个 CSV 文件读入单独的数据框中 [英] Read multiple CSV files into separate data frames
问题描述
假设我们在目录 C 中有文件 file1.csv、file2.csv、... 和 file100.csv:RData 并且我们希望将它们全部读入单独的数据帧(例如 file1、file2、... 和 file100).
Suppose we have files file1.csv, file2.csv, ... , and file100.csv in directory C:RData and we want to read them all into separate data frames (e.g. file1, file2, ... , and file100).
这样做的原因是,尽管名称相似,但它们的文件结构不同,因此将它们放在列表中并没有多大用处.
The reason for this is that, despite having similar names they have different file structures, so it is not that useful to have them in a list.
我可以使用 lapply
但它返回一个包含 100 个数据帧的列表.相反,我希望在全局环境中使用这些数据框.
I could use lapply
but that returns a single list containing 100 data frames. Instead I want these data frames in the Global Environment.
如何将多个文件直接读入全局环境?或者,如何将数据框列表的内容解压缩到其中?
How do I read multiple files directly into the global environment? Or, alternatively, How do I unpack the contents of a list of data frames into it?
推荐答案
快速草稿,未经测试:
使用
list.files()
又名dir()
动态生成文件列表.
Use
list.files()
akadir()
to dynamically generate your list of files.
这将返回一个向量,只需在 for
循环中沿着该向量运行即可.
This returns a vector, just run along the vector in a for
loop.
读取第 i 个文件,然后使用 assign()
将内容放入新变量 file_i
Read the i-th file, then use assign()
to place the content into a new variable file_i
这应该对你有用.
这篇关于将多个 CSV 文件读入单独的数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!