gpt4 book ai didi

r - 在 R 中按值传递

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

当尝试调用 grid.arrange 将多个图放在同一个 ggplot2 图上时,我首先构建了一个我想要的图的列表。然后我构建相应的参数列表来调用 grid.arrange,正如 in a previous question 所解释的那样.这是我的代码(我的数据框称为 manip):

args.list <- NULL;
plot.list <- NULL;
for (m in names(manip[2:10])) {
plot.list <- c(plot.list, list(qplot(manip$side, y=manip[,m],ylab=m))
}
args.list <- c(plot.list, 1, 9)
names(args.list) <- c(names(manip)[2:10], list("nrow","ncol"))
do.call(grid.arrange, args.list)

这是有效的,除了 9 个图是完全一样的!查了一下,原来数据始终是 m=10对应的那个。 .所以我的猜测是 m 的值未在循环中分配,但稍后进行评估。但是,标签 ylab=m 正确分配并且对于所有图形都不同。

所以我真的不明白有什么区别以及解释器如何选择何时评估 m 的情节。有人可以解释一下吗?

最佳答案

这种行为是由于 R 的惰性求值造成的。

这是一个最小(?)示例:

d <- 1:3

args.list <- NULL;
plot.list <- NULL;
for (m in 1:3) {
plot.list <- c(plot.list, list(qplot(d[m], d[m], ylab=letters[m])))
}

args.list <- c(plot.list, nrow=1, ncol=3)
do.call(grid.arrange, args.list)

在这种情况下, d[m]do.call 的调用中进行评估.所以 m所有面板为 3。

这是一个解决方法:
d <- 1:3

args.list <- NULL;
plot.list <- NULL;
for (m in 1:3) {
plot.list <- c(plot.list,
list(qplot(d, d, data=data.frame(d=d[m]), ylab=letters[m])))
}

args.list <- c(plot.list, nrow=1, ncol=3)
do.call(grid.arrange, args.list)

在这种情况下, d[m]qplot 的调用中进行评估,以及 d[m]存储在 qplot 的输出对象中。

因此,简单的解决方案是将数据传递给 qplot()ggplot() .

关于r - 在 R 中按值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7041204/

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