gpt4 book ai didi

R - 将对象存储在列表中

转载 作者:行者123 更新时间:2023-12-03 21:20:37 26 4
gpt4 key购买 nike

我正在尝试在 for 循环中生成不同的图并将它们保存到列表中。问题是这就像 plotly 的数据不是静态的,并且在每个循环中所有的图都在变化。
这是我的代码:

library(plotly)
data("iris")
names = names(iris)[-5]

plotList <- list()
for (i in 1:length(names)) {
for (j in 1:length(names)) {
name = paste("plot", i, j, sep = "_")
p <- (plot_ly(data = iris, x = ~get(names[i]), y = ~get(names[j]),
type = "scatter", mode = "markers") %>%
layout(
title = paste(names[i], names[j], sep = " vs "),
xaxis = list(title = names[i]),
yaxis = list(title = names[j])))
plotList[[name]] <- p
}
}

plotList$plot_4_3
plotList$plot_4_4

正如你所看到的,如果我查看列表的两个图,我得到了相同的结果,而如果我在没有 for 循环的情况下执行两个图,我得到了不同的结果,正确的结果:
i <- 4
j <- 3
p <- (plot_ly(data = iris, x = ~get(names[i]), y = ~get(names[j]),
type = "scatter", mode = "markers") %>%
layout(
title = paste(names[i], names[j], sep = " vs "),
xaxis = list(title = names[i]),
yaxis = list(title = names[j])))
p
i <- 4
j <- 4
p <- (plot_ly(data = iris, x = ~get(names[i]), y = ~get(names[j]),
type = "scatter", mode = "markers") %>%
layout(
title = paste(names[i], names[j], sep = " vs "),
xaxis = list(title = names[i]),
yaxis = list(title = names[j])))
p

我需要使 plotly 数据静态...

谢谢!

西维

最佳答案

添加 plotly_build :

library(plotly)
data("iris")
names = names(iris)[-5]

plotList <- list()
for (i in 1:length(names)) {
for (j in 1:length(names)) {
name = paste("plot", i, j, sep = "_")
plotList[[name]] <- plotly_build(plot_ly(data = iris, x = ~get(names[i]), y = ~get(names[j]),
type = "scatter", mode = "markers") %>%
layout(
title = paste(names[i], names[j], sep = " vs "),
xaxis = list(title = names[i]),
yaxis = list(title = names[j])))
}
}

plotList$plot_4_3
plotList$plot_4_4

关于R - 将对象存储在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54466628/

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