Loop with 2 levels in R
2
0
Entering edit mode
7.5 years ago
viniciushs88 ▴ 50

I would like analyze 17 probes separately, and each of them can be in a different chromosome. Then I have two levels: probes and chr:

probes <- c("BovineHD0500029561","BovineHD1100020616","BTB-00266062","BovineHD0200040828","BovineHD0100013622","BovineHD0100009413","BovineHD0300027356","BovineHD0600029053","BovineHD1500024004","BovineHD0200005954","BovineHD2900000062","BovineHD0200008162","BovineHD0400026684","BovineHD0200037832","BovineHD0300035509","Hapmap40156-BTA-103844","BovineHD0400022157")
chr <- c("chr5", "chr11", "chr12", "chr2", "chr1", "chr1", "chr3", "chr6", "chr15", "chr2", "chr29", "chr2", "chr4", "chr2", "chr3", "chr21", "chr4")


I would like to apply this loop:

{
probe <- c("probes")
pdf("boxplot""probes"".pdf")
boxplot(mat.num[,2], xlab="probes", ylab="LRR", main="probes")
}


I mean, repeat these above commands 17 times. The first with BovineHD0500029561==probes and chr5==chr ... and the last BovineHD0400022157==probes and chr4==chr.

Any suggestions? Cheers!

levels loop R • 3.0k views
1
Entering edit mode

I'm not quite sure if I understand you correctly. Am I right to assume that you want to apply the code to your 17 pairs of probe+chr? Is chr a placeholder for "chr5",... in "LRRadjustedall",chr,".txt"? Why do you declare probe <- c("probes") and don't use it afterwards?

0
Entering edit mode

I added an answer to what I think you want to do, however, the code you provided does not really make full use of the variables you provided.

0
Entering edit mode
7.5 years ago
t.candelli ▴ 60

You can iterate over the indexes of the two vectors "probes" and "chr".

here's the code, if I understood correctly what you want to do:

for (index in 1:length(probes))
{
probe <- probes[index]
pdf("boxplot""probes"".pdf")
boxplot(mat.num[,2], xlab="probes", ylab="LRR", main="probes")
}


this would iterate 17 times (the length of "probes") and at each iteration call the corresponding element of both "probes" and "chr" at the appropriate places

1
Entering edit mode

The "paste" is missing:

read.table(paste("LRRadjustedall",chr[index],".txt"), sep=";", header=TRUE)

0
Entering edit mode

correct, sorry I edited the answer

0
Entering edit mode
7.5 years ago
zx8754 10k

Following working example should get you started, it creates 3 PDF - 1 per probe, with 4 boxplots in each PDF, per chr:

#assign variables
probes <- c("BovineHD0500029561","BovineHD1100020616","BTB-00266062")
chr <- c("chr5", "chr11", "chr12", "chr2")

#loop through "probes"
sapply(probes,function(probe){
#PDF open
pdf(paste0("boxplot_",probe,".pdf"))
#loop through "chr"
sapply(chr,function(chrN){
#make dummy data
dat <- runif(100)
#boxplot dummy data
boxplot(dat, xlab=probe, ylab="LRR",
main=paste0(probe,"_",chrN))
})
#PDF close
dev.off()})