0

I need to import information from txt files. I used:

 in1 <- read.table("store1_in.txt", head = True)
 in2 <- read.table("store2_in.txt", head = True) 
...  

but it is not compact, so i was adviced to use cicles and vectors:

for (i in c(1:10)){
    input[i] <- read.table(file = paste0('store',i,'_in.txt'), head = TRUE)
  } 

but I received the warning message:

In input[i] <- read.table(file = paste0("store", i, "_in.txt"), :
number of items to replace is not a multiple of replacement length

What I did do wrong?

Dave2e
  • 22,192
  • 18
  • 42
  • 50
Anatolitr
  • 3
  • 1
  • `input <- lapply(list.files(pattern = 'store\\d+_in.txt'), read.table, header = TRUE)`. – Rui Barradas Apr 20 '20 at 15:51
  • Or create `input <- list('vector', 10)` first and inside the loop use `input[[i]]` with two `[[`. See [Difference between `[` and `[[`](https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el) – Rui Barradas Apr 20 '20 at 15:52

1 Answers1

0

From the code snippet it is not clear what input is. If it is a list, just use the double square brackets:

input <- list()

for (i in 1:10) {
  input[[i]] <- read.table(file = paste0('foo',i,'.txt'), header = TRUE)
}

However, I would use lapply instead:

input <- lapply(1:10, function(i) read.table(file = paste0('foo',i,'.txt'), header = TRUE))
tpetzoldt
  • 5,338
  • 2
  • 12
  • 29