I want a column of one table to be a sumproduct of two columns of another table as given in the following script. When I run the code in RStudio, the following error message is popping up: "Error in as: no method or default for coercing 'integer' to 'data.frame' ".
Can someone explain and amend, what is wrong in the script?
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)
The sumProduct1()
reactive expression returns a summarized data frame with one column containing the sumproduct. In your observe function, you're trying to assign this data frame directly to a single column of data$df2:
Change:
observe({data$df2$`Cost of goods available for sale` <- sumProduct1()})
with:
observe({
if(!is.null(sumProduct1())){
data$df2$`Cost of goods available for sale` <- sumProduct1()[[1]]
}
})