Using a counter inside an apply structured loop in R

邮差的信 提交于 2019-12-01 07:54:15

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
)

I think it might be easier to use loops in this case. Also, your code does not have a line to update the counter, like counter <- counter + 1. From inside apply you will need to assign to the global environment using <<-, note the doubled smaller < sign. An example using lapply, e.g.

Single lapply usage

counter <- 0
lapply(1:3, function(x) {
  counter <<- counter + 1
  cat("outer", counter, "\n")
  plot(1:10, main=counter)
})

Or nested usage of lapply

counter <- 0
lapply(1:3, function(x) {
  counter <<- counter + 1
  cat("outer", counter, "\n")
  lapply(1:3, function(x) {
    counter <<- counter + 1
    cat("inner", counter, "\n") 
    plot(1:10, main=counter)     
  })
})

I am not going to rewrite your code as I must say it is difficult to comprehend, but this will help: you can update a variable outside of the scope of apply by using <<- assignment, e.g. to update some external "counter"

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!