With
df <- data.frame(week = rep(1:7, each = 2), value = round(rnorm(14), 2))
I want to write out df into 7 (depending on the week column) separate files with each week as a single file. For instance:
1.tsv
1 0.49
1 1.04
2.tsv
2 0.40
2 0.97
...
7.tsv
7 -0.03
7 0.52
I came up with this:
for (wk in unique(df$week)) {
write.table(df[df$week == wk, ]
, file = paste(wk, ".tsv", sep = "")
, sep = "\t", row.names = F, col.names = F, quote = F)
}
but was curious if there is a better way to do the job without using a for loop.
Thanks!
You can often use the same construct you’re using inside a
forloop in function and combined with one of theapplyfamily:However, for clarity, I think the
forloop option is better. Also, the speed of the two will be very similar for an operation like this. The real advantage to theapplyfamily is when you need to “grow” a data structure whose size you cannot know before hand.