将多个 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屋!