Я настраиваю интерактивную панель с RShiny. Цель состоит в том, чтобы позволить выбранным пользователям ввести файл с оценками для указанных параметров. Я уже разработал регрессионную модель в ранее существовавшем файле R Script. Мой план состоит в том, чтобы использовать эту уже существующую модель для прогнозирования зависимой переменной с использованием параметров, загруженных пользователем.
Следующий сайт был особенно полезен: https://datascience -enthusiast.com / R / блестящая_ML.html . Однако мой код падает, когда я пытаюсь загрузить сохраненную модель (.rda) с помощью команды load () и с помощью source () сослаться на сценарий, откуда берется модель (.R).
я получаю следующую ошибку
«Предупреждение в файле (имя файла,« r », кодировка = кодировка):
невозможно открыть файл 'PolyFunct.R': нет такого файла или каталога
Предупреждение: ошибка в файле: не удается открыть соединение
[Нет трассировки стека] ”
Я пытался использовать load () и Source () над функцией ShinyServer и внутри нее. Оба не работают. Я попытался включить существующую модель как отдельный скрипт сохранения R и как функцию над функцией ShinyServer. Помощь будет оценена.
ETL = function(){
setwd("mydirectory")
fulldata <- read_excel("NoFines.xlsx")
finesdata <- read_excel("Model_Param.xlsx")
fulldata <- data.frame(fulldata)
finesdata <- data.frame(finesdata)
fulldata$FinesPerc <- NULL
fulldata$FinesDirectT <- NULL
return(fulldata)
return(finesdata)
} ##end of ETL function
PolyFunct = function(fulldata,finesdata){
library(caret)
library(leaps)
library(MASS)
library(DMwR)
mydata1 <- fulldata
mydata2 <- finesdata
mydata1$Comments <- NULL
mydata1$Date <- NULL
mydata2$Comments <- NULL
mydata2$Date <- NULL
ggpairs(mydata2)
#polynomial
PolyMod <- lm(mydata2$Recovery ~
polym(mydata2$007T,mydata2$007G,mydata2$FinesPerc, degree=2, raw=FALSE))
summary(PolyMod)
par(mfrow=c(2,2)) # init 4 charts in 1 panel
plot(PolyMod)
save(PolyMod , file = 'PolyRegression2.rda')
return(PolyMod)
}
ETL()
PolyFunct(fulldata,finesdata)
```
#setwd("mydirectory")
#load("PolyRegression.rda") # Load saved model
#source("PolyOnly.R")
library(shiny)
shinyServer(function(input, output) {
options(shiny.maxRequestSize = 800*1024^2)
output$sample_input_data_heading = renderUI({ # show only if data has
been uploaded
inFile <- input$file1
if (is.null(inFile)){
return(NULL)
}else{
tags$h4('Sample data')
}
}) #end show data upload
output$sample_input_data = renderTable({ # show sample of uploaded data
inFile <- input$file1
if (is.null(inFile)){
return(NULL)
}else{
input_data = readr::read_csv(input$file1$datapath, col_names = TRUE)
colnames(input_data) = c("007T","007G","FinesPerc")
head(input_data)
}
}) #end show sample of uploaded data
predictions<-reactive({
load("PolyRegression.rda") # Load saved model
source("PolyFunct.R",encoding="utf-8",local = TRUE)
inFile <- input$file1
if (is.null(inFile)){
return(NULL)
}else{
withProgress(message = 'Predictions in progress. Please wait ...', {
input_data = readr::read_csv(input$file1$datapath, col_names = TRUE)
colnames(input_data) = c("007T","C007G","FinesPerc")
input_data$Recovery = predict(PolyMod, input_data)
})
}
})## end of predictions
output$sample_prediction_heading = renderUI({ # show only if data has been uploaded
inFile <- input$file1
if (is.null(inFile)){
return(NULL)
}else{
tags$h4('Sample predictions')
}
}) ## end of sample prediction headings
output$sample_predictions = renderTable({ # the last 6 rows to show
pred = predictions() ##call the reactive function above where predictions are made
head(pred)
})
# Downloadable csv of predictions
output$downloadData <- downloadHandler(
filename = function() {
paste("input_data_with_predictions", ".csv", sep = "")
},
content = function(file) {
write.csv(predictions(), file, row.names = FALSE)
})
})