Nazer
Nazer

Reputation: 3774

Loop for writing multiple dataframes to excel files in R

I have been splitting up dataframes and writing them to txt files in R, but now I've found out that they need to be written to xlsx files. I installed the xlsx package and modified my loop, but it doesn't work anymore. I get "Error in [[.default(dots[[2L]], 1L) : subscript out of bounds".

Here is the loop:

trts<-vector("list", length=6)
trt<-as.character(c("CC", "CCW", "C2", "S2", "PF", "P"))

for(i in 1:6){
trts[[i]]<-co2[co2$trt == trt[i],]
  write.xlsx(trts[[i]], paste(trt[i], "CO2", "xlsx", sep="."))

Here is the data (my df is co2): Split this.

What's the deal?

Upvotes: 1

Views: 1467

Answers (1)

zx8754
zx8754

Reputation: 56249

Why not just output it as CSV?

#Read Data
co2 <- read.table("~/Observed COBS CO2.txt",
                                header=T, quote="\"")

#Output to CSV
apply(as.matrix(unique(co2$trt)),1,
      function(x){
        write.table(co2[co2$trt == x,],
                    paste(x, "co2",".csv",sep=""),
                    sep=",",row.names=F)}
      )

Upvotes: 1

Related Questions