Rain Man
Rain Man

Reputation: 1263

Write to files in R using a loop

I have several variables as follow:

cats <- "some long text with info"
dogs <- "some long text with info"
fish <- "some long text with info"
....

and I manually write the content of these variables into a text file:

write.table(cats, "info/cats.txt", sep="\t")
write.table(dogs, "info/dogs.txt", sep="\t")
....

I read the answer to this question and tried to write a loop to automatically write the files.

So I created a list:

lst <<- list(cats, dogs,fish, ....)

and then iterated through the list:

for(i in seq_along(lst)) {
    write.table(lst[[i]], paste(names(lst)[i], ".txt", sep = ""), 
               col.names = FALSE, row.names = FALSE,  sep = "\t")
}

but the output of the above iteration is one text file called .txt and it contains the content of the last variable in the list.

any idea why the above loop doesn't work as expected?

Upvotes: 0

Views: 2438

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57686

Note the following:

> cats <- "some long text with info"
> dogs <- "some long text with info"
> fish <- "some long text with info"
> lst <- list(cats, dogs,fish)  # not <<-
> names(lst)
NULL

When you created your list, you didn't give it any names, so your loop doesn't have anything to work with. A fix:

> names(lst) <- c("cats", "dogs", "fish")

Upvotes: 6

Related Questions