最近,我正在尝试创建一个交互式的闪亮应用程序。在这个应用程序中,我希望使用线性模型来预测用户的给定值。同样,预测变量和解释变量可以由用户选择。此后,模型仅返回应用程序显示的预测值。但是,我无法弄清楚如何让应用使用现有的数据框并返回预测值。运行该应用程序时,出现以下错误:
Warning in storage.mode(v) <- "double" : NAs introduced by coercion
Warning: Error in contrasts<-: contrasts can be applied only to factors with 2 or more levels
[No stack trace available]
该脚本本身类似于Sean Kross(https://seankross.com/developing-data-products/shiny.html#reactivity)的代码。我使用下面显示的脚本导致了错误:
librar(shiny)
#Create random data frame with three vectors
df <- data.frame(V1=1:100, V2=100:1*runif(100, min=0, max=1), V3=1:100*runif(100, min=0, max=1))
ui <- fluidPage(
headerPanel("Regression"),
sidebarPanel(
p("Select explanatory variable"),
selectInput(inputId = "ExpVar", label = "Explanatory variable", choices = colnames(df)),
p("Select predictor variable"),
selectInput(inputId = "PreVar", label = "Predictor variable", choices = colnames(df)),
numericInput(inputId = "Pred", label = "Predict chosen value", value = 10),
h3("Prediction"),
textOutput("prediction")))
server <- function(input, output){
modpred <- reactive({
Pre <- input$Pred
Pname <- input$PreVar
mod <- lm(input$PreVar~input$ExpVar, data=df)
predict(mod, newdata = data.frame(Pname = Pre))})
output$prediction <- renderText({modpred()})
}
shinyApp(ui, server)
提前感谢您的时间
可能有不同的方法。一种可能是使用varSelectInput
,然后从df
中的ui
中选择变量名(这将返回一个符号)。
这里我们离开selectInput
并使用字符串。在使用lm
之前,您将需要基于这些字符串创建公式,因为它们不是符号。
为此,您可以使用as.formula
或reformulate
(后者在这里完成)。这将生成您的公式(例如V2 ~ V1
)。
此外,对于predict
,您希望将new_df
的列名设置为Pname
。先前的代码将把列本身命名为Pname
,而不是Pname
等于的字符串。
modpred <- reactive({
Pre <- input$Pred
Pname <- input$PreVar
mod <- lm(reformulate(input$PreVar, input$ExpVar), data=df)
new_df <- data.frame(Pre)
names(new_df) <- Pname
predict(mod, newdata = new_df)
})