【发布时间】:2016-08-29 20:44:10
【问题描述】:
我遇到了一个我无法解决的奇怪问题。
以下代码在 R studio 中运行良好:
> set.seed(12345)
>
> library(plyr)
> library(dplyr)
>
> dt <- data.frame(a=1:10, b=sample(1:3, 10, replace=T))
>
> var <- "a"
> formula <- parse(text=paste0(var, "+1"))[[1]]
>
> print(dt)
a b
1 1 3
2 2 3
3 3 3
4 4 3
5 5 2
6 6 1
7 7 1
8 8 2
9 9 3
10 10 3
>
> # this works in R Studio, but not in markdown
> res <- dt %>%
+ ddply(.(b), transform, diff = eval(formula))
> print(res)
a b diff
1 6 1 7
2 7 1 8
3 5 2 6
4 8 2 9
5 1 3 2
6 2 3 3
7 3 3 4
8 4 3 5
9 9 3 10
10 10 3 11
当我在 R markdown 中运行相同的代码时,我收到一条错误消息,提示
Error: arguments imply differing number of rows: 2, 0
这里发生了什么?这是我的降价代码:
---
title: "Untitled"
author: "Author"
date: "8/29/2016"
output: html_document
runtime: shiny
---
```{r}
set.seed(12345)
library(plyr)
library(dplyr)
dt <- data.frame(a=1:10, b=sample(1:3, 10, replace=T))
formula <- parse(text=paste0("a", "+1"))[[1]]
#this does work in R, but not in markdown
res <- dt %>%
ddply(.(b), transform, diff = eval(formula))
res
```
谢谢
【问题讨论】:
-
无法复制。我机器上的结果和上面介绍的一样。
-
您是否运行了 Markdown 文档中的最后一段代码?代码在 r studio 中运行,而不是在 r markdown 中。
-
@chungkim721 我把你的代码保存到文件中,在 RStudio 中使用
rmarkdown::run运行这个东西,并且能够通过 Chrome 中的 localhost 访问该应用程序。您是否部署在服务器上,或者您所说的“in r markdown”到底是什么意思? -
这看起来像是一个闪亮的运行时错误。 rmarkdown 工作正常。
-
如果您使用
eval(parse(...)),通常有更好的方法。见fortunes::fortune(106)。
标签: r plyr r-markdown