-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
  • 433
  • 1
  • 6
  • 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
  • `L <- lapply(paste0(type,".txt"), read.table, header=TRUE)` gives a list of dataframes. `names(L) <- type` sets the names. – jogo Mar 23 '17 at 12:43

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,814
  • 11
  • 19
0

Try this:

for (type in c("fr","no","sta","sto")){
      as.name(type) <- read.table(paste0(type,".txt"), header=TRUE)
}
989
  • 12,579
  • 5
  • 31
  • 53
Liun
  • 117
  • 2
  • Thanks, but I got an error " Error in as.name(type) <- read.table(paste0(type, ".txt"), header = TRUE) : could not find function "as.name<-" " – user3631848 Mar 23 '17 at 13:46
  • I'm sorry for that and try this `for (type in c("fr","no","sta","sto")){ eval(parse(text = paste0(type,"<-read.table(\"",type,".txt","\",header=TRUE)"))) }` – Liun Mar 24 '17 at 23:51
  • another solution like this `for (type in c("fr","no","sta","sto")){ assign(type,read.table(paste0(type,".txt"))) }` – Liun Mar 25 '17 at 00:15