Reputation: 165
Here, I'm looking at the file mtcars in R. This is one loop that can be used to write columns into 11 separate files, since there are 11 columns in the dataset.
for(i in (1:length(mtcars[1, ])))
write.table(mtcars[i], file=paste("mtcars", as.character(i), ".txt",
sep=""), row.names=FALSE, sep="\t");
I'm just curious, how would you do this if you were to change it into writing all columns into separate files? Right now, I know one modification to make would be that we set the first line length parameter to mtcars[,1] instead, but I'm curious what you can substitute the i with? Are there any other substitutions that need to be made in other parts of the code?
Edit: missing quote
Upvotes: 2
Views: 1771
Reputation: 4024
Your code already writes each column into a separate file. Do you want to replicate the whole table 11 times? In that case, just write.table(mtcars, ...
Edit: Try this:
for(i in 1:nrow(mtcars)
write.table(mtcars[i,], file=paste("matchers", as.character(i), ".txt",
sep=""), row.names=FALSE, sep="\t")
Or without a for loop:
sapply(mtcars, 1:nrow(mtcars), function(i)
write.table(mtcars[i,],
file=paste0("matchers", i, ".txt"),
row.names=FALSE, sep="\t") )
Or
library(dplyr)
mtcars %>%
mutate(index = 1:n() )
rowwise %>%
do(write.table(.,
file=paste0("matchers", .$index, ".txt"),
row.names=FALSE, sep="\t") )
Upvotes: 3