问题
I have the dataframe below:
DF2 = data.frame(agency_postcode = factor(rep(c(12345,45678,24124,32525,32325),2)),
car_group=factor(rep(c("Microcar","City car","Supermini","Compact","SUV"),2)),
transmission=factor(rep(c("automatic","manual"),5)))
and after subseting it by one of the values of the 1st column
newdata <- DF2[ which(DF2$agency_postcode =='12345'), ]
and re-factoring in order to set accordingly the dropdown values of the second and third column to only available values after the subset
for(i in 2:ncol(newdata)){
newdata[,i] <- factor(newdata[,i])
}
I display it with:
library(rhandsontable)
rhandsontable(newdata[1,], rowHeaders = NULL, width = 550, height = 300)%>%
hot_col(colnames(newdata))
What I want to do is when I select a different value from the available ones of (only) the 1st column the whole table should be updated accordingly if of course this row exists.
回答1:
You would need to assign the newdata dataframe and the postcode selected as reactive values and trigger the render function using this reactive value. A working example.
library(shiny)
library(rhandsontable)
ui <- fluidPage(
titlePanel("RHandsontable"),
sidebarLayout(
sidebarPanel(),
mainPanel(
rHandsontableOutput("test")
)
)
)
server <- function(input, output) {
# Assign value of 12345 as default to postcode for the default table rendering
values <- reactiveValues(postcode = "12345",tabledata = data.frame())
# An observer which will check the value assigned to postcode variable and create the sample dataframe
observeEvent(values$postcode,{
DF2 = data.frame(agency_postcode = factor(rep(c(12345,45678,24124,32525,32325),2)),
car_group=factor(rep(c("Microcar","City car","Supermini","Compact","SUV"),2)),
transmission=factor(rep(c("automatic","manual"),5)))
# Created dataframe is assigned to a reactive dataframe 'tabledata'
values$tabledata <- DF2[ which(DF2$agency_postcode ==values$postcode), ]
for(i in 2:ncol(values$tabledata)){
values$tabledata[,i] <- factor(values$tabledata[,i])
}
})
# Capture changes made in the first column of table and assign the value to the postcode reactive variable. This would then trigger the previous observer
observeEvent(input$test$changes$changes,{
col <- input$test$changes$changes[[1]][[2]]
if(col==0){
values$postcode <- input$test$changes$changes[[1]][[4]]
}
})
# Use the reactive df 'tabledata' to render.
output$test <- renderRHandsontable({
rhandsontable(values$tabledata[1,], rowHeaders = NULL, width = 550, height = 300)%>%
hot_col(colnames(values$tabledata))
})
}
shinyApp(ui = ui, server = server)
Hope this helps!
来源:https://stackoverflow.com/questions/57925696/update-rhandsontable-by-changing-one-cell-value