2

请考虑这个功能:

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
    }

您可以使用它运行:

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

groups将论点传递给我做错了什么xyplot-为什么找不到?我无法弄清楚它如何想要这些group信息。谢谢。

更新:

@agstudy 的回答很有帮助,但是如果我像原始示例一样添加面板功能,仍然无法识别组(没有分组,但也没有发生错误):

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
    }

仍然缺少一些东西...谢谢。

4

2 回答 2

4

您可以eval在此处使用,因为match.call返回符号。

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
}
于 2013-02-09T07:01:23.100 回答
2

当我在函数内定义和调用函数时遇到问题时,我使用的一种技术是将参数作为字符串传递,然后从这些字符串构造函数内的调用。这就是这里的样子。

panel2 <- function(x, y, ...) {panel.stripplot(x, y, jitter.data = TRUE, pch = 20, ...)}
tf <- function(formula, data, groups) {
  eval(call("xyplot", as.formula(formula), 
                      groups=as.name(groups), 
                      data=as.name(data),
                      panel=as.name("panel2")))
}

tf("mpg~vs", "mtcars", "am") 

有关此示例的另一个示例,请参见我之前的一个问题的答案:https ://stackoverflow.com/a/7668846/210673 。

另请参阅此问题的姐妹问题的答案,我建议使用类似的方法aovhttps ://stackoverflow.com/a/14858614/210673

于 2013-02-13T16:50:18.460 回答