请考虑此功能:
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
}
仍然缺少某些东西......谢谢。
答案 0 :(得分: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
}
答案 1 :(得分: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。
另请参阅此问题的姐妹问题的答案,我建议使用与aov
类似的内容:https://stackoverflow.com/a/14858614/210673