自定义晶格函数作用域(组参数) [英] Scoping in custom lattice functions (group argument)

查看:79
本文介绍了自定义晶格函数作用域(组参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下功能:

tf <- function(formula = NULL, data = NULL, groups = NULL) {

    grv <- eval(substitute(groups), data, environment(formula)) # the values
    grn <- as.character(match.call()$groups) # the name
    gr <- match.call()$groups # unquoted name

    p <- xyplot(formula, data, # draws the data but not in groups
# Try these options:
#   p <- xyplot(formula, data, groups, # can't find 'cat2' 
#   p <- xyplot(formula, data, groups = data[,grn], # can't fine grn
#   p <- xyplot(formula, data, groups = grv, # can't find grv
        panel = function(x, y) {
            panel.stripplot(x, y, jitter.data = TRUE, pch = 20)
            }
            )
    p
    }

您可以使用以下哪一种:

Which you can run with:

tf(formula = mpg~vs, groups = am, data = mtcars)

在将groups参数传递给xyplot时,我做错了什么-为什么找不到它?我不知道它怎么想要group信息.谢谢.

What am I doing wrong in passing the groups argument to xyplot - why can't it be found? I can't figure out how it wants the group information. Thanks.

更新:

@agstudy的答案非常有帮助,但是如果我像原始示例中那样添加面板功能,则仍无法识别组(不进行分组,但也不会发生错误):

@agstudy's answer is very helpful, but if I add the panel function as in the original example, the groups are still not recognized (no grouping, but no error occurs either):

tf <- function(formula = NULL, data = NULL, groups = NULL) {
    ll <- as.list(match.call(expand.dots = FALSE)[-1])
    p <- xyplot(as.formula(ll$formula), 
              data = eval(ll$data), 
              groups = eval(ll$groups),
                panel = function(x, y) {
                panel.stripplot(x, y, jitter.data = TRUE, pch = 20)
                }
                )
    p
    }

仍然缺少某些东西...谢谢.

Something is still missing... Thanks.

推荐答案

由于match.call返回符号,因此可以在此处使用eval.

You can use eval here since match.call returns symbols.

tf <- function(formula = NULL, data = NULL, groups = NULL) {
  ll <- as.list(match.call(expand.dots = FALSE)[-1])
  p <- xyplot(as.formula(ll$formula), 
              data = eval(ll$data), 
              groups = eval(ll$groups),
              panel = function(x, y,...) { ## here ... contains groups and subscripts
                ## here you can transform x or y before giving them to the jitter
                panel.stripplot(x, y, jitter.data = TRUE, pch = 20,...)
              }
  )
  p
}

这篇关于自定义晶格函数作用域(组参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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