在運行下面的 MWE 代碼時,它可以很好地運行插值場景。但是,如果我注釋掉interpol()當前未注釋的第一個自定義函式,并取消注釋第二個interpol()函式,則不會繪制結果。為什么??它們在輸出形式上非常相似!
我interpol()在 R Studio 控制臺中運行了兩個版本進行測驗。他們都按他們應該的方式作業。我跑時它們都是向量,我跑is.vector()時它們都是數字is.numeric()。
顯然,第二個interpol()不插值,它計算一個 sumproduct(測驗 sumproduct 以進行此代碼的演變)。在默認情況下,它生成一個包含 10 個元素的向量,每個元素 = 5。為什么這不會像第一個那樣繪制interpol()?
MWE代碼:
library(shiny)
library(shinyMatrix)
library(dplyr)
library(ggplot2)
interpol <- function(a, b) { # a = periods, b = matrix inputs
c <- rep(NA, a)
c[1] <- b[1]
c[a] <- b[2]
c <- approx(seq_along(c)[!is.na(c)], c[!is.na(c)], seq_along(c))$y
return(c)
}
# interpol <- function(a, b) { # a = periods, b = matrix inputs
# c <- rep(NA, a)
# c[] <- sum(b[,1]) %*% sum(b[,2])
# return(c)
# }
ui <- fluidPage(
sliderInput('periods', 'X-axis periods:', min=1, max=10, value=10),
matrixInput(
"myMatrixInput",
label = "Values to sumproduct paired under each scenario heading:",
value = matrix(c(1, 5), 1, 2, dimnames = list(NULL, rep("Scenario 1", 2))),
cols = list(extend = TRUE, delta = 2, names = TRUE, delete = TRUE, multiheader = TRUE),
rows = list(extend = FALSE, delta = 1, names = FALSE, delete = FALSE),
class = "numeric"),
plotOutput("plot")
)
server <- function(input, output, session) {
observeEvent(input$myMatrixInput, {
tmpMatrix <- input$myMatrixInput
# Remove any empty matrix columns
empty_columns <- sapply(tmpMatrix, function(x) all(is.na(x) | x == ""))
tmpMatrix <- tmpMatrix[, !empty_columns, drop=FALSE]
# Assign column header names
colnames(tmpMatrix) <- paste("Scenario", rep(1:ncol(tmpMatrix), each = 2, length.out = ncol(tmpMatrix)))
isolate( # isolate update to prevent infinite loop
updateMatrixInput(session, inputId = "myMatrixInput", value = tmpMatrix)
)
})
plotData <- reactive({
tryCatch(
lapply(seq_len(ncol(input$myMatrixInput)/2),
function(i){
tibble(
Scenario = colnames(input$myMatrixInput)[i*2-1],
X = seq_len(input$periods),
Y = interpol(input$periods, input$myMatrixInput[1,(i*2-1):(i*2)])
)
}) %>% bind_rows(),
error = function(e) NULL
)
})
output$plot <- renderPlot({
req(plotData())
plotData() %>% ggplot() geom_line(aes(
x = X,
y = Y,
colour = as.factor(Scenario)
))
})
}
shinyApp(ui, server)
uj5u.com熱心網友回復:
為了更容易解釋,我將第一個函式稱為interpol1,第二個函式稱為interpol2。
在lapply您呼叫函式 ( interpol(input$periods, input$myMatrixInput[1,(i*2-1):(i*2)])) 的地方input$myMatrixInput[1,(i*2-1):(i*2)]回傳一個數字向量而不是矩陣。在interpol1您使用b[1]和b[2]對值進行子集化時,其值b是對向量進行子集化的正確方法,但在interpol2您使用b[,1]和b[,2]對不正確并回傳錯誤的向量進行子集化時Error in b[, 1] : incorrect number of dimensions。我認為您希望b成為一個矩陣,因此您使用了b[, 1].
一種解決方法是將輸入保留為矩陣,這可以通過使用 -
Y = interpol1(input$periods, input$myMatrixInput[1,(i*2-1):(i*2), drop = FALSE])
這應該適用于函式interpol1和interpol2.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/326979.html
上一篇:獲取資料框中特定值的列名和行名
下一篇:如何找到我的混淆矩陣的準確性?
