我希望一个表的一列是另一个表的两列的和积,如以下脚本所示。当我在 RStudio 中运行代码时,会弹出以下错误消息:“Error in as: no method or default for coercing 'integer' to 'data.frame'”。
有人可以解释并修改,脚本中有什么问题吗?
library(shiny)
library(shinydashboard)
library(rhandsontable)
library(data.table)
library(dplyr)
DF1 = data.table(
"Batch"= as.character(),
"Amount of goods"= as.numeric(0),
"Unit cost of goods"= as.numeric(0),
stringsAsFactors=FALSE)
DF2= data.table(
"Cost of goods available for sale" = as.numeric(0),
"Cost of goods sold" = as.numeric(0),
stringsAsFactors=FALSE)
ui <- dashboardPage(
dashboardHeader(title = "Accounting"),
dashboardSidebar(
menuItem("Home", tabName = "home"),
menuItem("Measurement", tabName = "measurement",
menuSubItem("Inventory", tabName = "table1")
)
),
dashboardBody(
tabItems(
tabItem(
tabName = "table1",
column(
"DF1",
width = 12,
rHandsontableOutput("Table1")
),
column(
"DF2",
width = 12,
rHandsontableOutput("Table2")
)
)
)
)
)
server <- function(input, output, session) {
data <- reactiveValues()
observe({
input$recalc
data$df1<- as.data.frame(DF1)
data$df2 <- as.data.frame(DF2)
})
observe({
if(!is.null(input$Table1))
data$df1<- hot_to_r(input$Table1)
})
observe({
if(!is.null(input$Table2))
data$df2 <- hot_to_r(input$Table2)
})
sumProduct1<-reactive({data$df1%>%
summarize(sum(`Amount of goods` * `Unit cost of goods`))})
observe({data$df2$`Cost of goods available for sale` <- sumProduct1()})
output$Table1 <- renderRHandsontable({
rhandsontable(data$df1, stretchH = "all") |>
hot_cols(colWidths = c(300, 150, 150))
})
output$Table2 <- renderRHandsontable({
rhandsontable(data$df2, stretchH = "all") |>
hot_cols(colWidths = c(150, 150))
})
}
shinyApp(ui, server)
sumProduct1()
反应式表达式返回一个汇总数据框,其中一列包含和积。在您的观察函数中,您尝试将此数据框直接分配给单列数据 $df2:
改变:
observe({data$df2$`Cost of goods available for sale` <- sumProduct1()})
与:
observe({
if(!is.null(sumProduct1())){
data$df2$`Cost of goods available for sale` <- sumProduct1()[[1]]
}
})