使用R中的apply结构化循环内的计数器

Kat*_*808 4 plot counter r apply

我试图从R中相当复杂的数组进行绘制.我想生成一个包含3×3图形的图像,每个图形上都有红色和蓝色点.

我有一个应用循环的结构,但我想改变每行的y最大值.

我通常会使用像我这样的计数器在其他语言中这样做.但R中的应用事情让我感到困惑!

par(mfrow=c(3,3),pty="s")             # a 3 by 3 graphic
set.seed(1001)

x <- 1:54                             # with 1 to 54 along the x axis

y <- array(rexp(20), dim=c(54,6,3,2)) # and the y axis coming 
                                      # from an array with dimensions as shown.

ymax <- c(1,0.1,0.3)                  # three different y maximum values I want 
                                      # on the graphic, one for each row of graphs

counter <- 1                          # a counter, starting at 1, 
                                      # as I would use in a traditional loop

apply(y[,3:5,,], 2, function(i)       # my first apply, which only considers
                                      # the 3rd, 4th and 5th columns
    {

    yy <- ymax[counter]               # using the counter to select my ylimit maximum

    apply(i, 2, function (ii)         # my second apply, considering the 3rd 
                                      # dimension of y
        {
            plot(x,ii[,1], col="blue", ylim=c(0,yy)) 

                                      # plotting the 4th dimension

                points(x,ii[,2], col="red") 

                                      # adding points in a different 
                                      # colour from the 4th dim. 

    })
})
Run Code Online (Sandbox Code Playgroud)

提前感谢您的想法,非常感谢!

干杯凯特

Mar*_*ann 9

我认为在这种情况下使用循环可能更容易.此外,您的代码没有更新计数器的行,例如counter <- counter + 1.从内部apply您将需要使用分配给全局环境<<-,请注意加倍的小<符号.使用lapply例如的示例

lapply

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

或嵌套使用 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)     
  })
})
Run Code Online (Sandbox Code Playgroud)


Bro*_*ieG 8

这里的关键是在索引上而不是在数组本身上使用lapply,因此您可以使用索引将y限制和内部循环之前的数组子集化.这也避免了必须使用该<<-构造.

简化了您的数据:

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
)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述