Using a counter inside an apply structured loop in R

后端 未结 3 1549
Happy的楠姐
Happy的楠姐 2021-01-12 15:27

I\'m trying to plot from a rather complex array in R. I want to produce an image with 3 by 3 graphs, each with red and blue points on it.

I\'ve got a structure of a

3条回答
  •  有刺的猬
    2021-01-12 15:46

    The key thing here is to use lapply on the index rather than on the array itself, so then you can use the index to subset both your y limits and the array ahead of the inner loop. This also avoids having to use the <<- construct.

    Simplified your data a bit:

    par(mfrow=c(3,3),pty="s")             # a 3 by 3 graphic
    set.seed(1001)
    x <- 1:10                             # with 1 to 54 along the x axis
    dims <- c(10,6,3,2)
    y <- array(rexp(prod(dims)), dim=c(10,6,3,2)) # and the y axis coming 
    ymax <- c(1,0.1,0.3)
    
    lapply(1:3, function(counter, arr) {
      apply(
        arr[ ,counter + 2, , ], 2, 
        function(ii) {
          plot(x, ii[,1], col="blue", ylim=c(0,ymax[counter]))
          points(x, ii[,2], col="red") 
        } )
      },
      arr=y
    )
    

    enter image description here

提交回复
热议问题