Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write many files in a for loop

Tags:

r

I have sample data like this

df <- data.frame(name = rep(letters[1:7], each = 24), salary = runif(24*7, 100, 200))

I wanted to separate each name with their salaries

lst <- tapply(df$salary, df$name, matrix, nrow = 4, byrow = TRUE)

Now I want to write all these 7 matrices to 7 different text files, It is working only for a single matrix at a time. I tried to put in a for loop but is not working

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

Can any one suggest for the modifications in the for loop?

like image 353
Matt Avatar asked Aug 11 '11 22:08

Matt


People also ask

Can you write to two files at once in Python?

Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files.

How do I save multiple text files in Python?

You can merge multiple text files to a single CSV file in Python by using the glob. glob('./*. txt') expression to filter out all path names of text files in a given folder. Then iterate over all those path names and use the open() function to read the file contents and write append them to the CSV.


1 Answers

Given your lst, the following will write this out to a series of TXT files with names equal to the name of lst, plus .txt:

lapply(names(lst),
       function(x, lst) write.table(lst[[x]], paste(x, ".txt", sep = ""),
                                    col.names=FALSE, row.names=FALSE, sep="\t", 
                                    quote=FALSE),
       lst)

To modify your for() loop, try:

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

The problem was trying to or assuming R would paste together the filenames for you.

like image 90
Gavin Simpson Avatar answered Oct 04 '22 03:10

Gavin Simpson