0

I simply need to save df each time it goes through the loop and save it as a csv or something similar!

#Q are matrices and trees are phyllo objects

library(ape)
library(phytools)

for(l in 1:length(Q.all)){
for(k in 1:length(trees)){

tree<- trees[[k]]
Q<- Q.all[[l]]

file1<- sim.history (tree, Q, nsim=10)

df<- getStates(file1, type="tips")

df2 <- as.data.frame(matrix(nrow=nrow(df),ncol=length(file1)))

for(i in 1:length(file1)){  
  for(j in 1:nrow(df)){ 
    x <- df[j,i]
    num <- sum(df[,i] == x) - 1 
    rarity <- 1 - num/(nrow(df)-1)             
    df2[j,i] <- rarity
  }
}

Thanks

Jack
  • 165
  • 2
  • 12
  • 2
    `write.csv(df, file = paste0(i, "_", j, ".csv"))` – Gregor Thomas Dec 23 '15 at 22:47
  • it saves it all in one big csv? should I put it in the loop? or where? I mean df id being overwritten again and again ! – Jack Dec 23 '15 at 22:57
  • I'm just going off of your sentence *"save df each time it goes through the loop"*. Based on that, the code written saves `df`, the whole object, whatever you have in it at the time of saving. If you want to save it "each time it goes through the loop", then put the command inside the loop! Things that are outside the loop don't happen "each time through the loop". You'll notice the `i` and `j` being used in the filename for the csv, so this will save a brand new csv at each loop iteration, if you put it inside the loop. – Gregor Thomas Dec 24 '15 at 01:13
  • Your question is pretty vague... you talk about "the loop", but you have four loops. You're missing some syntax (the `l` and `k` loops have no closing brace), and it's not close to reproducible because we don't have the definitions for a bunch of your objects. If you need more help you need to help us help you by making [your example reproducible](http://stackoverflow.com/q/5963269/903061). You would probably do well to slash most of the code and try to make a **minimal** example of saving a data frame in a loop. – Gregor Thomas Dec 24 '15 at 01:18
  • Thanks for your help, Gregor! – Jack Jan 05 '16 at 21:52

0 Answers0