This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Loop with 2 levels in R

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:

{
chr2 <- read.table("LRRadjustedall",chr,".txt", sep=";", header=TRUE)
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

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?

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.

2 answers

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))
{
chr2 <- read.table(paste("LRRadjustedall",chr[index],".txt"), sep=";", header=TRUE)
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

The "paste" is missing:

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

correct, sorry I edited the answer

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()})

Log in to answer this question.