Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import multiple text files in R and assign them names from a predetermined list

Tags:

text

import

r

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")

Is there a way to use a command such as *apply to automate the process?

like image 345
Mike Ferguson Avatar asked Mar 19 '11 02:03

Mike Ferguson


People also ask

How do I read multiple files in R studio?

In order to read multiple CSV files or all files from a folder in R, use data. table package. data. table is a third-party library hence, in order to use data.


2 Answers

            files <- list.files(pattern = 'Patient*.txt')    
            for(i in files) {
            x <- read.table(i, header=TRUE, comment.char = "A", sep="\t")
            assign(i,x)  
            }
like image 190
Rabaie Remon Avatar answered Sep 23 '22 18:09

Rabaie Remon


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.

like image 17
Ramnath Avatar answered Sep 20 '22 18:09

Ramnath