r - 将数据框列提供给 xyplot 面板函数

标签 r plot lattice

我在数据框上使用 xyplot,并且想要向面板函数提供不是 (x,y, ...) 参数的数据,而是数据框的一些附加列(例如下面示例中的 k) ):

library(lattice)

mydata <- data.frame(xxx = 1:20,
                     yyy = rbinom(20,20,.5),
                     uuu = gl(2,10),
                     k = rnorm(20))

xyplot( formula = yyy ~ xxx | uuu, data = mydata,
        panel = function(x,y,k, ...){
                n <- x * k
                panel.xyplot(n,y,...)
                })

我知道这行不通,因为 R 不会将此 k 列提供给面板函数。有没有简单的方法可以做到这一点?

(我不想在实际面板函数中将 x 乘以 k。我正在调用另一个需要 k 的函数...)

非常感谢!

最佳答案

这就是有用的(但有些晦涩的)subscripts 参数的用途。来自?xyplot中“panel”参数的描述:

[...] the panel function can have 'subscripts' as a formal argument. In either case, the 'subscripts' argument passed to the panel function are the indices of the 'x' and 'y' data for that panel in the original 'data', BEFORE taking into account the effect of the 'subset' argument.

换句话说,名为“subscripts”的正式参数将包含 data 参数中与当前面板中绘制的数据相对应的行号 - 正是您需要挑选的内容k 值的所需子集。

根据您的情况,请执行以下操作:

xyplot(yyy ~ xxx | uuu, data = mydata, K = mydata$k, pch=16, 
       panel = function(x,y,K, ..., subscripts){
                   n <- x * K[subscripts]
                   panel.xyplot(n,y,...)
               })

(请注意,此应用程序中有一个奇怪的复杂情况。名为 kxyplot() 参数将被解释为 key,由于参数部分匹配。为了防止这种情况,我将相关参数命名为 K,以便将其完整地传递给面板函数。)

关于r - 将数据框列提供给 xyplot 面板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16020581/

相关文章:

r - 如何在 GGPLOT theme_classic() 中启用 x 轴和 y 轴

R 尾声 "The leading minor of order 3 is not positive definite"

r - Zeppeling Docker镜像中缺少R解释器

python - 使用 python +/- matplotlib 绘制机器人路径和方向

R - 从数据帧创建散点图

r - 在 r 中的多个数据帧上应用一组操作

c++ - 你如何在QT中绘制点?

r - 如何在不使用外部包的情况下在 R 中制作漂亮的双标图?

cryptography - 使用 Palisade 库的同态加密

r - 在 ggplot 或点阵中使用 Surv 对象