如何根据文件名将多个csv文件加载到R中的单独对象(数据帧)中?
我知道如何使用以下方法轻松加载整个 .csv 文件文件夹:
csv_files = list.files(pattern ="*.csv")
myfiles = lapply(csv_files, read.delim, header = FALSE)
然后我可以轻松地迭代“myfiles”它们并执行我想要的任何操作。我遇到的问题是这只是加载工作目录中的所有 .csv 文件。
我想做的是能够根据文件名将文件分配给脚本中的对象。
举例来说,在一个目录中我有这些文件;文件001、文件002、文件003 和exfile001、exfile002、exfile003。
我希望能够以这样的方式加载它们,
file_object <- file...
exfile_object <- exfile...
这样当我执行脚本时,它基本上会执行我为 file_object 编程的任何操作(在本例中分配为 file001)& exfile_object(在此示例中指定为 exfile001)。然后继续以这种方式处理目录中的其余文件(例如 file002、exfile002、file003、exfile003)。
我知道如何在 MATLAB 中做到这一点,但我刚刚开始掌握 R。
我想也许使用 list.files 函数将它们放入单独的列表中可能只需更改脚本中的工作目录即可,但这看起来很混乱并且需要重新-写下我的情况...
谢谢!
I know how to load a whole folder of .csv files quite easily using:
csv_files = list.files(pattern ="*.csv")
myfiles = lapply(csv_files, read.delim, header = FALSE)
From which I can then easily iterate over 'myfiles' them and do whatever I wish. The problem I have is this simply loads all the .csv files in the working directory.
What I would like to do is be able to assign the files to objects in the script based on the filename.
Say, for example, in one directory I have the files; file001, file002, file003 and exfile001, exfile002, exfile003.
I want to be able to load them in such away that
file_object <- file...
exfile_object <- exfile...
So that when I execute the script it essentially does whatever i've programmed it to do for file_object(assigned as file001 in this example) & exfile_object(assigned as exfile001 in this example). Then goes on to continue in this way for the rest of the files in the directory (eg. file002, exfile002, file003, exfile003).
I know how to do it in MATLAB, but am just getting to grips with R.
I thought perhaps getting them into seperate lists using the list.files function may work by just changing working directory in script, but it seems messy and would involve re-writing things in my case...
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
任何好奇的人的解决方案...
本质上在循环中构建文件名,然后在每次迭代时将其传递给 readcsv 函数。
Solution for anyone curious...
Essentially build the filename within the loop, then passs it to the readcsv function on each iteration.
如果您的框架列表
myfiles
使用以下方式命名:那么您可以
将这些单独的框架转换为全局环境中的单独对象。
If your list of frames,
myfiles
is named using this:then you can do
to convert those individual frames to separate objects in the global environment.