【问题标题】:For loop over dygraph does not work in RFor loop over dygraph 在 R 中不起作用
【发布时间】:2015-08-11 03:45:24
【问题描述】:

dygraph 上有一些奇怪的行为。

当为dygraph 使用for 循环时,我没有得到任何结果。

library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)

for(i in 1:2){
  dygraph(lungDeaths[, i])
}

另一方面,当我使用lapply 时,我确实得到了预期的结果

lapply(1:2, function(i) dygraph(lungDeaths[, i]))

我实际上想在我自己的数据集上使用R Markdown 中的for 循环并迭代不同的列,但即使我使用lapply“解决方法”,它也不会绘制dygraphs

R Markdown 代码

---
title: "Untitled"
author: "dimitris_ps"
date: "28 May 2015"
output: html_document
---

```{r}
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
lapply(1:2, function(i) dygraph(lungDeaths[, i]))
```

而当我逐列运行它时它可以工作

---
title: "Untitled"
author: "dimitris_ps"
date: "28 May 2015"
output: html_document
---

```{r echo=FALSE}
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
```

```{r}
dygraph(lungDeaths[, 1])
dygraph(lungDeaths[, 2])
```

任何帮助将不胜感激。

会话信息

R version 3.2.0 (2015-04-16)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252   
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] dygraphs_0.4.3 devtools_1.7.0

loaded via a namespace (and not attached):
[1] htmltools_0.2.6 tools_3.2.0     yaml_2.1.13     rmarkdown_0.6.1 digest_0.6.8 

【问题讨论】:

  • lapplymarkdown 中为我工作。至于for loop,你可以使用show(dygraph(lungDeaths[, i]))来解决问题(效率低下)
  • 感谢您对此进行调查。不幸的是,对我来说两者都不起作用。我将用我的sessionInfo() 更新我的问题
  • 我使用的是相同的 R 版本加上 '0.4.3' dygraphs 版本。
  • 这里也一样。这很奇怪。我已经在 2 台不同的机器上尝试过,但问题仍然存在。
  • 当我在for loop 工作中说lapplyshow 选项时,我的意思是我只能在viewer 中看到html。可能这与dynamic chart 有关。您可以就此向软件包维护者发送电子邮件。

标签: r r-markdown dygraphs


【解决方案1】:

对于任何在循环中苦苦挣扎的人,这对我有用。

p=list()
for (n in 1:3){
  p[[n]] <- plot_ly(x = 1:100, y = rnorm(100)+n, mode = 'lines', type="scatter")
}
htmltools::tagList(p)

即列表 p 是在循环中创建还是在 lapply 等中创建都没有关系,只要您在循环外调用 htmltools::tagList。

感谢 Yihui 帮助我实现目标,并在开发和帮助这些工具方面付出了巨大的努力。

【讨论】:

  • 如果你想添加一些关于这个答案的评论——比如它是否是一个重复的答案——你可以把它放在你的答案下面的 cmets 中。
  • 附加提示:必须使用 renderUI 而不是 renderDygraph
【解决方案2】:

只需将lapply() 的列表输出包装在htmltools::tagList() 中,例如

```{r}
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
res <- lapply(1:2, function(i) dygraph(lungDeaths[, i]))
htmltools::tagList(res)
```

【讨论】:

  • 谢谢你的大师。
  • 为了闪亮,在服务器中使用 renderUI( htmltools::tagList(res) ),然后在 UI 中使用 htmlOutput()。 (而不是 renderDygraph() 和 dygraphOutput())。这是一个在 Shiny 中帮助我的例子:mail-archive.com/r-help@r-project.org/msg246267.html
猜你喜欢
  • 1970-01-01
  • 2016-04-24
  • 2018-11-29
  • 1970-01-01
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多