-3

I have many text files

fr.txt
no.txt
sta.txt
sto.txt

I create a vector with filename as string

string <- c("fr","no","sta","sto")

And I would like to use for loop in R to use string as the variable names and to read the corresponding files.

for (type in c("fr","no","sta","sto")){type <- read.table(sprintf("%s.txt", type),header=TRUE)}

For example

fr <- read.table("fr.txt",header=TRUE)
no <- read.table("no.txt",header=TRUE)
sta <- read.table("sta.txt",header=TRUE)

How should I start with ? The above for loop failed to do what I want.

user3631848
  • 313
  • 1
  • 4
  • 14
  • 1
    *"The above for loop failed to do what I want."* -- what does this mean *specifically*? Also, you are missing a comma before `header = TRUE` in `read.table(sprintf("%s.txt", type) header=TRUE)`. – nrussell Mar 23 '17 at 11:30
  • See gregor's answer to [this post](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for some tips that may help. – lmo Mar 23 '17 at 11:33
  • 2
    Don’t use different variable names, use a list. – Konrad Rudolph Mar 23 '17 at 11:40

2 Answers2

0

If you want to read all ".txt" files in a directory just use:

temp = list.files(pattern="*.txt")
myfiles = lapply(temp, read.table)

Explained
list.files() - grabs your files in your working directory. Suppose you saved your files ("one.txt", "two.txt" etc.) in "C://example" then you have to set your working directory first like

setwd("C://example")
so that list.files() would know where to search your files. You could also list .csv files if needed by using:
temp = list.files(pattern="*.csv")

Following that now you can apply read.table function for each ".txt" file in your working directory by using:

lapply(temp, read.table)
Aleksandr
  • 1,776
  • 10
  • 19
0

Try this:

for (type in c("fr","no","sta","sto")){
      as.name(type) <- read.table(paste0(type,".txt"), header=TRUE)
}
989
  • 11,865
  • 5
  • 27
  • 49
Liun
  • 117
  • 2