kvaibhav
kvaibhav

Reputation: 163

Load multiple files in corresponding variable in R

Is there a way of saying something like:

for (i in 1:10){
  ga${i} <- read.table(file="ene.${i}.dat",header=T, sep = ",")
}

in R.

I tried using many other constructs, but none suited the requirement.

Thanks.

Upvotes: 0

Views: 403

Answers (2)

Artem Klevtsov
Artem Klevtsov

Reputation: 9423

We can extract file names first.

ga <- lapply(list.files(path = ".", pattern = "\\.dat"), read.csv)

or with loop:

lf <- list.files(path = ".", pattern = "\\.dat")
ga <- structure(vector("list", length(lf)),
                names = gsub("\\.dat", "", lf))
for (i in seq_along(ga))
    ga[i] <- read.csv(lf[i])

To assign data to the separate variables:

lf <- list.files(path = ".", pattern = "\\.dat")
fn <- gsub("\\.dat", "", lf)
for (i in seq_along(lf))
    assign(fn[i], read.csv(lf[i]))

Upvotes: 2

Gopala
Gopala

Reputation: 10473

You can use an empty list and then a paste function to do something like this:

ga <- list()
for (i in 1:10) {
  ga[[i]] <- read.table(file = paste('ene.', i, '.dat', sep = ''), header = TRUE, sep = ',')
}

Then, you will have a list of data frames. You can index as ga[[1]], ga[[2]] etc. to access them.

Upvotes: 1

Related Questions