Valentin Lauret
Valentin Lauret

Reputation: 1

R_ How to put a variable in a name

I have 50 files to read in R and I created this loop to help me. I would like to know if it is possible to do something like this in R.
How can I write it properly in R?

library(foreign)    
for(i in 1:50 ){
      tpi <- read.dbf('toto_%i%')
     }

Help please.

Upvotes: 0

Views: 56

Answers (2)

Se&#241;or O
Se&#241;or O

Reputation: 17412

You want to use the function paste. As written your loop will overwrite tpi everytime it increments, so you will want to use a list to store the data.

toto = list()
for(i in 1:50)
{
    toto[i] = read.dbf(paste0("toto_", i))
}

A shortcut using lapply gets the same results:

toto = lapply(1:50, function(x) read.dbf(paste0("toto_", x)))

Upvotes: 1

akrun
akrun

Reputation: 886938

We can do this using lapply

lst <- lapply(1:50, function(i) read.dbf(paste0("toto_", i)))

Upvotes: 1

Related Questions