在R中的Apply结构化循环内使用计数器 [英] Using a counter inside an apply structured loop in R

查看:106
本文介绍了在R中的Apply结构化循环内使用计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我有一个适用的Apply循环结构,但是我想按每行更改y最大值.

I've got a structure of apply loops which works, but I'd like to change the y maximum value by each row.

我通常会使用其他语言的计数器(例如i)来执行此操作.但是R中的apply东西完全让我感到困惑!

I would normally do this using a counter, like i, in other languages. But the apply thing in R is completely baffling me!

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. 

    })
})

预先感谢您的想法,非常感谢!

Thank you in advance for your thoughts, they are very much appreciated!

欢呼 凯特

推荐答案

此处的关键是对索引而不是数组本身使用lapply,因此您可以使用索引对y限制和内循环之前的数组.这也避免了必须使用<<-构造.

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.

稍微简化了您的数据:

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
)

这篇关于在R中的Apply结构化循环内使用计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆