Я пытаюсь использовать ggplot2 для построения прогноза цены акций в R Shiny.Тем не менее, я получаю сообщение об ошибке:
Предупреждение: ошибка в as.data.frame.default: невозможно принудительно привести класс 'c ("gg", "ggplot")' к data.frame[Трассировка стека недоступна]
Вот моя функция прогнозирования и мой код сервера.
library(shiny)
library(shinydashboard)
library(devtools)
library(ggvis)
library(dplyr)
library(RSQLite)
library(ggplot2)
library(randomForest, quietly = TRUE)
library(lubridate)
# Forecasting Function ----------------------------------------------------
getdfnew <- function(df){
# clean up data frame to set types appropriately
df$Stock.Trading <- as.numeric(df$Stock.Trading)
# Build the training/validate/test datasets.
nobs <- nrow(df)
ntr <- 0.2*nobs # assumes first 20% of data tunes good system
set.seed(42)
str(df)
indices.train <- 1:ntr #
indices.apply <- (ntr+1):nobs #
input.variables <- c("Open",
"High","Low",
"Close","Volume")
input.numbers <- c("Open",
"High","Low",
"Close","Volume")
target.variable <- "Stock.Trading"
set.seed(42)
result.rf <- randomForest::randomForest(Stock.Trading ~ .,
data=df[indices.train ,c(input.variables, target.variable)],
ntree=500,
mtry=3,
importance=TRUE,
na.action=randomForest::na.roughfix,
replace=FALSE)
# Get predicted and actual values
predicted.training <- result.rf$predicted
actual <- df$Stock.Trading
# Apply model to new data -------------------------------------------------
df.apply <- df[indices.apply, c(input.variables, target.variable)]
# Lets say we had new data ---- data.new
# It's essential that the new data have the same input columns and target(s)
# new.data <- newdataset[1:nrows(newdataset),c(crs$input, crs$target)]
# predict for each of the validate indices the wear condition
predicted.apply <- predict(result.rf, df.apply , type="response",
norm.votes=TRUE, predict.all=FALSE, proximity=FALSE, nodes=FALSE)
predicted.all <- vector(length=nobs)
predicted.all[1:ntr] <- predicted.training
predicted.all[(ntr+1):nobs] <- predicted.apply
df$Predicted <- predicted.all
colnames(df)[8] <- "Predicted"
return(df)
}
Код сервера для этой вкладки:
output$rfplot <- renderTable({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
df <- read.csv(inFile$datapath, header=input$header, sep=input$sep,
quote=input$quote)
dfnew <-getdfnew(df)
x <- dfnew$Stock.Trading
y <- dfnew$Predicted
# browser()
dfnew$DATE <- as.Date(parse_date_time(dfnew$Date, "%m/%d/%y"))
p <- ggplot(dfnew, aes(DATE)) +
geom_line(aes(y = Stock.Trading, colour = "Actual")) +
geom_line(aes(y = Predicted, colour = "Predicted"))
print(p)
})
Имой набор данных выглядит так:
Date Open High Low Close Volume Stock.Trading
12/30/2016 42120 42330 41700 41830 610000 25628028000
12/29/2016 43000 43220 42540 42660 448400 19188227000
12/28/2016 43940 43970 43270 43270 339900 14780670000
12/27/2016 43140 43700 43140 43620 400100 17427993000
12/26/2016 43310 43660 43090 43340 358200 15547803000
Любая помощь будет признательна!