Search code examples
rloopslevels

Loop with 2 levels in R


I would like to use this strings:

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")

In 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, repeate these above commands 17 times. The first with BovineHD0500029561==probes and chr5==chr ... and the last BovineHD0400022157==probes and chr4==chr.

Any sugestions? Cheers!


Solution

  • If the following output for the pairs is correct:

    for (i in 1:length(probes)) {
      cat(probes[i])
      cat(", ")
      cat(chr[i])
      cat("\n")
    }
    ## BovineHD0500029561, chr5
    ## BovineHD1100020616, chr11
    ## BTB-00266062, chr12
    ## BovineHD0200040828, chr2
    ## BovineHD0100013622, chr1
    ## BovineHD0100009413, chr1
    ## BovineHD0300027356, chr3
    ## BovineHD0600029053, chr6
    ## BovineHD1500024004, chr15
    ## BovineHD0200005954, chr2
    ## BovineHD2900000062, chr29
    ## BovineHD0200008162, chr2
    ## BovineHD0400026684, chr4
    ## BovineHD0200037832, chr2
    ## BovineHD0300035509, chr3
    ## Hapmap40156-BTA-103844, chr21
    ## BovineHD0400022157, chr4
    

    then:

    for (i in 1:length(probes)) {
      chr2 <- read.table("LRRadjustedall",chr[i],".txt", sep=";", header=TRUE)
      pdf(sprintf("boxplot%s.pdf", probes[i]))
      boxplot(mat.num[,2], xlab=probes[i], ylab="LRR", main="probes")
    }
    

    should work for you, but

    • is this is truly a simple "how to use a basic for loop with indexing" question?
    • you never use chr2 in your loop.