Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feeding data frame columns to xyplot panel functions

Tags:

plot

r

lattice

I am using xyplot on a data frame and want to feed a panel function with data that is not the (x,y, ...) arguments, but some additional column of the data frame (say k in the example below):

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,...)
                })

I understand that this will not work, because R does not feed this k column to the panel function. Is there a simple way to do so?

(I'm not trying to just multiply x by k in my actual panel function. I'm calling another function that requires k...)

Many thanks!

like image 257
Max Avatar asked Apr 15 '13 16:04

Max


1 Answers

This is what the useful (but somewhat obscure) subscripts argument is for. From the description of the "panel" argument in ?xyplot:

[...] 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.

In other words, a formal argument named "subscripts" will contain the row numbers in your data argument that correspond to the data being plotted in the current panel -- just what you need to pick out the desired subset of the k-values.

In your case, do:

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,...)
               })

(Note that there was one odd complication in this application. An argument to xyplot() named k will get interpreted as key, due to partial matching of arguments. To prevent that, I named the relevant argument K so that it would be passed, intact, to the panel function.)

like image 53
Josh O'Brien Avatar answered Sep 20 '22 16:09

Josh O'Brien