我最近在閃亮的Google小組中發佈了類似的查詢,但沒有找到解決方案。我們正在開發一個Shiny應用程序,並且該主題表明我們在運行應用程序時遇到了「錯誤:下標越界」消息。但是,當我們隔離有問題的代碼並在RStudio中獨立運行代碼時,沒有錯誤。爲什麼Shiny中出現「下標越界」錯誤,但不是R?
這讓我想知道Shiny本身是否存在缺陷,或者我們是否缺少某些東西。
請參閱下面的說明以及產生錯誤的小例子。我們使用Shiny版本0.8.0和RStudio 0.98.501。
感謝您的幫助!
運行應用程序,將ui.R和server.R(見下文)的文件夾中,然後運行
library(shiny)
runApp("<folder path>")
它應該產生與左邊的按鈕的用戶界面,但在右邊你會看到「error:subscript out of bounds」。
但是,如果只是運行的代碼下面三行(大約57-59行中server.R)
show=data.frame(ps=c(4,-1,0,1),ns=c(0,1,0,0),ts=c(45842,15653,28535,21656))
best.fit1=regsubsets(ts~ps+ns,data=show,nvmax=1)
pred1=predict.regsubsets(best.fit1,show,id=1) # line that offends Shiny
在RStudio(需要包含的功能「predict.regsubsets」 - 在給定的server.R的開頭),那麼就沒有錯誤。
#####################
## server.R
#####################
library(rms)
library(leaps)
library(shiny)
library(datasets)
library(stringr)
library(ttutils)
library(plyr)
library(utils)
library(ggplot2)
# object is a regsubsets object
# newdata is of the form of a row or collection of rows in the dataset
# id specifies the number of terms in the model, since regsubsets objects
# includes models of size 1 up to a specified number
predict.regsubsets=function(object,newdata,id,...){
form=as.formula(object$call[[2]])
mat=model.matrix(form,newdata)
mat.dims=dim(mat)
coefi=coef(object,id=id)
xvars=names(coefi)
# because mat only has those categorical variable categories associated with newdata,
# it is possible that xvars (whose variables are defined by the "best" model of size i)
# has a category that is not in mat
diffs=setdiff(xvars,colnames(mat))
ndiffs=length(diffs)
if(ndiffs>0){
# add columns of 0's for each variable in xvars that is not in mat
mat=cbind(mat,matrix(0,mat.dims[1],ndiffs))
# for the last "ndiffs" columns, make appropriate names
colnames(mat)[(mat.dims[2]+1):(mat.dims[2]+ndiffs)]=diffs
mat[,xvars]%*%coefi
}
else{
mat[,xvars]%*%coefi
}
}
# Define server logic required to summarize and view the selected dataset
shinyServer(function(input, output) {
mainTable1 <- reactive({
})
output$table21 <- renderTable({
mainTable1()
})
formulamodel1 <- reactive({
#ticketsale<-dataset1Input()
show=data.frame(ps=c(4,-1,0,1),ns=c(0,1,0,0),ts=c(45842,15653,28535,21656))
best.fit1=regsubsets(ts~ps+ns,data=show,nvmax=1)
pred1=predict.regsubsets(best.fit1,show,id=1)
})
output$model1fit <- renderPrint({
formulamodel1()
})
})
######################
## end server.R
######################
######################
## ui.R
######################
library(rms)
library(leaps)
library(shiny)
library(datasets)
library(stringr)
library(ttutils)
library(plyr)
library(utils)
library(ggplot2)
shinyUI(pageWithSidebar(
headerPanel("Forecasting ticket sales for xxx"),
sidebarPanel(
p(strong("Model Fitting")),
selectInput("order1", "Sort results by:",c("a","b","c")),
submitButton("Run Model")
),
mainPanel(
h3(strong("Model fit without using ticket sales")),
tableOutput("table21"),
verbatimTextOutput(outputId = "model1fit")
)
))
喬,謝謝你的迴應。您正確識別了該問題。 Google小組中的某人能夠幫助我們。再次感謝。 – user3596572