1

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?

5
  • 1
    What is the problem actually? Commented Jul 22, 2013 at 15:34
  • Sorry, I get "Error in [[.default(dots[[2L]], 1L) : subscript out of bounds". Commented Jul 22, 2013 at 15:54
  • 1
    Usually that happens if you do something like List[[7]] for a list of length < 7 or something. Try adding print(i) as a line in your loop and see if you can figure out which one is giving you the problem. Commented Jul 22, 2013 at 16:17
  • Thanks for the tip, @Senor O, but I'm not sure I understand what is printed. It is just the numbers 1,2,3. I thought it would go up to six. But this exact codes works when making txt files, just not for excel files. Commented Jul 22, 2013 at 20:12
  • Exactly - it would go up to 6 if your loop worked correctly. Now you know that your loop stops working sometime in between print(3) and print(4). Commented Jul 22, 2013 at 20:24

1 Answer 1

1

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

5 Comments

I guess because with a .csv the person using excel won't be able to just double click on it and open it. They have to go through the extra steps of telling excel that it is a .csv. I'll end up with about 50 files, so I'm hoping R can make things smoother for that person. Thanks for the non-loop code though!
Double clicking on .csv file just opens same way as any Excel file.
Yeah! That's what I thought, but other .csv files I have written from R are opening with all of my text in the first column. I haven't run your code yet, but I'll try that and see if it clears up the problems I didn't know I was having before I tried .xlsx.
Yep! Thanks a lot! Wonder why I have been using .txt anyway. . .
If it was helpful, upvoting would help.

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.