读取单独的文本文件,并将它们保存在单个变量中作为单独的数据帧 [英] Reading seperate text files and saving them in a single variable as seperate dataframes

查看:78
本文介绍了读取单独的文本文件,并将它们保存在单个变量中作为单独的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个从同一软件生成的文本文件(制表符分隔).最初,我使用了带有Assign函数的循环来动态创建变量,并将其与read.table函数分开存储.这导致了太多的变量,并且显然在将操作应用于单独的文件上非常耗时.

I have multiple text files (tab-delimited) generated from the same software. I initially used a loop with assign function to create variables dynamically and store them separately with the read.table function. This resulted in too many variables and was obviously time-consuming to apply operations on separate files.

我遇到了下面代码中显示的lapply和fread方法.

I came across the lapply and fread method shown in the code below.

我不需要合并它们,它们需要是单独的数据框,因此我可以比较文件中的值.使用lapply函数,这是可能的,但是文件名没有以任何方式保留.我从>如何一次导入多个.csv文件中找到了以下代码? 帮了我大忙.它有多行,我想知道是否有单行解决方案.

I don't need to merge them and they need to be separate data frames so I can compare values in the files. Using the lapply function, this was possible but the file names were not retained in any way. I found the following code from How to import multiple .csv files at once? that helped me with it. It has multiple lines and I was wondering whether there is a one-line solution for this.

foo <- function(fname){
  fread(fname, skip = 5, header = TRUE, sep = " ") %>% 
   mutate(fn = fname)
}

all <- lapply(files, FUN = foo)

或者,如何在lapply中访问特定的迭代?

Alternatively, how do I access the specific iteration in lapply?

推荐答案

我们可以使用setNames

all <- setNames(lapply(files, foo), files)

这篇关于读取单独的文本文件,并将它们保存在单个变量中作为单独的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆