在 R 中导入多个文本文件并从预先确定的列表中为其指定名称 [英] Import multiple text files in R and assign them names from a predetermined list
问题描述
我刚开始使用 R,但在执行以下任务时遇到问题:我的工作目录中包含大约 130 个单独的纯文本文件中的语言示例.我想做的是使用扫描导入它们并保留它们的文件名.具体来说,我想做的是使用类似的东西:
I just started using R and I am having trouble performing the following task: I have approximately 130 language samples in separate plain text files sitting in my working directory. What I would like to do is import them using scan and retain their file names. Specifically, what I would like to do is using something like:
Patient01.txt <-scan("./Patient01.txt", what = "character")
Patient02.txt <-scan("./Patient02.txt", what = "character")
...
Patient130.txt <-scan("./Patient130.txt", what = "character")
有没有办法使用诸如 *apply 之类的命令来自动化该过程?
Is there a way to use a command such as *apply to automate the process?
推荐答案
这是自动化流程的一种方法
Here is one way to automate the process
# read txt files with names of the form Patient*.txt
txt_files = list.files(pattern = 'Patient*.txt');
# read txt files into a list (assuming separator is a comma)
data_list = lapply(txt_files, read.table, sep = ",")
如果您知道分隔符是什么,您可以更改它.将数据保存为数据框列表很方便,因为以后更容易投入向量化操作或循环.
You can change the separator if you know what it is. It is convenient to keep the data as a list of data frames since it is easier to throw into a vectorized operation or loops later.
这篇关于在 R 中导入多个文本文件并从预先确定的列表中为其指定名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!