我的数据框如下:
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)))
,并根据第一列的值之一对它进行子集化
newdata <- DF2[ which(DF2$agency_postcode =='12345'), ]
并进行重构,以便将第二和第三列的下拉值设置为仅子集之后的可用值
for(i in 2:ncol(newdata)){
newdata[,i] <- factor(newdata[,i])
}
我将其显示为:
library(rhandsontable)
rhandsontable(newdata[1,], rowHeaders = NULL, width = 550, height = 300)%>%
hot_col(colnames(newdata))
我想做的是,当我从(仅)第一列的可用值中选择一个不同的值时,如果此行存在,则应该相应地更新整个表。
答案 0 :(得分:1)
您需要分配 newdata 数据框和邮政编码作为反应性值,并使用该反应性值触发渲染功能。一个可行的例子。
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)
希望这会有所帮助!