代码运行但在r中编织时给出错误

时间:2018-06-13 12:00:01

标签: r r-markdown knitr

当我们在markdown中运行块代码时,此代码运行正常。

```{r , echo = FALSE, results='asis', comment=NA, warning=FALSE, message=FALSE}
options("getSymbols.warning4.0"=FALSE)
options("getSymbols.yahoo.warning"=FALSE)
library(plyr)
library(knitr)
library(ggplot2)
library(quantmod)
library(lubridate)
library(scales)
comp.name <- readline(prompt = "Enter the company name: ")
tyu2 <- getSymbols(comp.name , src = "yahoo", verbose = TRUE, from = "2018-03-01", auto.assign = FALSE)
tyu2 <- as.data.frame(tyu2)
tyu <- tyu2[,6]
x <- row.names(tyu2)
final <- length(tyu)
final <- as.numeric(final)
p <- ggplot(data = tyu2 , aes(x= x ,y=tyu))+geom_bar(stat = "identity", fill = "blue")+ theme(axis.text.x = element_text(angle = 90))
p
```

但是当尝试使用降价编织时,它会给出错误

Error in `[.data.frame`(tyu2, , 6) : undefined columns selected
Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> [ -> [.data.frame

这个错误是什么意思。如何解决。请帮忙。在线找到安装所有包的答案。安装好所有东西。

1 个答案:

答案 0 :(得分:3)

您的代码有一行用于用户输入。但是,假设用户没有输入任何内容,knitr将跳转到下一行。这意味着comp.name""getSymbols()检索空数据,这意味着所有列在技术上都是未定义的。

我建议进行以下更改:

```{r , echo = FALSE, results='asis', comment=NA, warning=FALSE, message=FALSE}
options("getSymbols.warning4.0"=FALSE)
options("getSymbols.yahoo.warning"=FALSE)
library(plyr)
library(knitr)
library(ggplot2)
library(quantmod)
library(lubridate)
library(scales)
comp.name <- readline(prompt = "Enter the company name: ")
# For case user inpt is empty
if (comp.name == "") {
  comp.name <- "AAPL"
}
tyu2 <- getSymbols(comp.name , src = "yahoo", verbose = TRUE, from = "2018-03-01", auto.assign = FALSE)
tyu2 <- as.data.frame(tyu2)
tyu <- tyu2[,6]
x <- row.names(tyu2)
final <- length(tyu)
final <- as.numeric(final)
p <- ggplot(data = tyu2 , aes(x= x ,y=tyu))+geom_bar(stat = "identity", fill = "blue")+ theme(axis.text.x = element_text(angle = 90))
p
```

我能够很好地编织这个。