gpt4 book ai didi

r - 自定义格函数(组参数)中的范围

转载 作者:行者123 更新时间:2023-12-02 08:43:08 25 4
gpt4 key购买 nike

请考虑这个函数:

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
}

有些东西仍然缺失......谢谢。

最佳答案

您可以在此处使用 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
}

关于r - 自定义格函数(组参数)中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14784302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com