0

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?

3
  • is.null(names(lst)); #[1] TRUE Commented Mar 8, 2016 at 20:04
  • @nrussell that returns TRUE Commented Mar 8, 2016 at 20:05
  • 1
    Yes -- you did not name your list. Equivalently, paste0(NULL, ".txt") Commented Mar 8, 2016 at 20:07

1 Answer 1

6

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")
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, I thought the name is automatically selected from the list
Named arguments will become list names, e.g., list = list(cats = cats, name_of_dog_item = dogs, fish_here = fish) will have names "cats", "name_of_dog_item", etc.
Alternatively, mget will name your list automatically: mget(c("cats", "dogs", "fish")).
@HongOoi is it possible to create a loop for the first part too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.