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

后端 未结 2 895
梦如初夏
梦如初夏 2020-12-05 12:24

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 di

相关标签:
2条回答
  • 2020-12-05 12:59
                files <- list.files(pattern = 'Patient*.txt')    
                for(i in files) {
                x <- read.table(i, header=TRUE, comment.char = "A", sep="\t")
                assign(i,x)  
                }
    
    0 讨论(0)
  • 2020-12-05 13:03

    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.

    0 讨论(0)
提交回复
热议问题