Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当qplot的参数包含list时,多个qplot对R中一个图形的奇怪性能_R_Ggplot2 - Fatal编程技术网

当qplot的参数包含list时,多个qplot对R中一个图形的奇怪性能

当qplot的参数包含list时,多个qplot对R中一个图形的奇怪性能,r,ggplot2,R,Ggplot2,目标:将多个Qplot保存到图形中。 关键是有一个列表参数要循环(见代码,更清楚!)。输出与我预期的不同。他们是一样的 # Make y be a list containing different values. y <- list() for (j in 1:6) { y[[j]] <- rnorm(10) } # plot multi qplots into one figure plots <- list() # new empty list for (i

目标:将多个Qplot保存到图形中。 关键是有一个列表参数要循环(见代码,更清楚!)。输出与我预期的不同。他们是一样的

# Make y be a list containing different values.
y <- list()
for (j in 1:6) {
    y[[j]] <- rnorm(10)
}

# plot multi qplots into one figure
plots <- list()  # new empty list
for (i in 1:6) {
    p1 = qplot(1:10, y[[i]],  main = i)
    plots[[i]] <- p1  # add each plot into plot list
}
do.call(grid.arrange, plots)

这与传递给
qplot
的参数的延迟检查有关。在打印绘图之前,不会实际解析这些值。此时,循环后if
i
的值仅为6。更好的策略是

plots <- lapply(1:6, function(i) {
    force(i) #required if you didn't have main=i to force the evaluation of i
    qplot(1:10, y[[i]],  main = i)
})
do.call(grid.arrange, plots)

图的答案真是出乎我意料。当然,这是正确的。在这种情况下,我几乎无法识别lappy和for循环之间的任何区别。区别在于
lappy
中调用的函数具有不同的环境,而for循环在相同的环境中计算所有参数。对于这种lappy的用法,还有其他实用程序吗?非常感谢。
plots <- lapply(1:6, function(i) {
    force(i) #required if you didn't have main=i to force the evaluation of i
    qplot(1:10, y[[i]],  main = i)
})
do.call(grid.arrange, plots)