I need to do a loop with several conditions (create three diferent objects several times) and with a loop nested. I write this:
`metaxcan <- c("foo1.csv", "foo2.csv")`
`predix_asso <- c("soo1.csv", "soo2.csv")`
`for (i in metaxcan){`
`for (j in predix_asso){`
`PGC<-read.csv(i, header=T, sep=",")`
`asociacion<-read.table(j, header=T, sep="") `
`PGC_predix <- merge(PGC,asociacion,by="gene")`
`ngenes<-nrow(PGC_predix_1) `
`print(ngenes)`
`}`
`}`
But instead of print just 2 numbers (the merge between foo1 and soo1; and the merge of foo2 and soo2), it prints 4 numbers (all interactions)
How can I do? thanks
1 answer
But instead of print just 2 numbers (the merge between foo1 and soo1; and the merge of foo2 and soo2), it prints 4 numbers (all interactions)
4 numbers makes sense because you're merging: foo1 + soo1, foo1 + soo2, foo2 + soo1, foo2 + soo2 and printing the ngenes after each j loop.
Sounds like you want to do them pairwise (foo1 + soo1, foo2 + soo2). If that's the case, you could do something like:
for (index in length(metaxcan) ) { # Assuming they're the same size as predix_asso.
i = metaxcan[index] # Obtain them pairwise
j = predix_asso[index]
PGC<-read.csv(i, header=T, sep=",")
asociacion<-read.table(j, header=T, sep="")
PGC_predix <- merge(PGC,asociacion,by="gene")
ngenes<-nrow(PGC_predix_1)
print(ngenes)
}
Log in to answer this question.
Not sure if that question really fits here, but for now your code is faulty:
PGC_predix_1 is undefined, or possibly defined elsewhere in your environment, maybe PGC_predix was meant. That is why you get the same output, the number of rows in this variable. It prints 4 times, because i and j each have two elements and 2x2=4.
If your file name vectors always have the same length then there is no need of nested loop, the single loop should work.
for example:
Hello julrodr80!
We believe that this post does not fit the main topic of this site.
Pure R question, please search StackOverflow
For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.
If you disagree please tell us why in a reply below, we'll be happy to talk about it.
Cheers!