gpt4 book ai didi

r - 通过多列中的值在 R shiny 中有效地过滤数据框

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:08:25 24 4
gpt4 key购买 nike

我想知道一种有效的方法来执行以下操作。在 Shiny 的应用程序中使用响应式 dataframe()。我想要两个 react 性输入(每个都有 2 种可能性 TRUEFALSE),它们分别根据两列中的值对行进行子集化。如果我只有一个输入(和一列 photos),我会这样做:

df<-reactive({
df<-mydf
if(input$myinput==FALSE)
{
df<-df[!df$photos=="",]
}
else{
df
}
})

问题是如果我有两个(或更多)输入(和列),如果我在 ifelse 在上面的示例中,允许两个 TRUE/FALSE 输入的 4 种可能性。

编辑:可重现,无需太多 ifelse 即可使第二个输入工作:

server <- function(input, output, session) { 
df<-reactive({
df<-iris
if(input$Petalw==T)
{
df<-df[df$Petal.Width==0.2,]
}
else{
df
}
})
output$table <- DT::renderDataTable(
DT::datatable(df(), options = list(searching = FALSE,pageLength = 25))
)
}
ui <- navbarPage(
title = 'Select values in two columns based on two inputs respectively',
fluidRow(
column(width = 3,
checkboxInput("Petalw","PetalWithIs0.2",T),
checkboxInput("PetalL","PetalLengthis1.4",T)
),
column(9,
tabPanel('Table', DT::dataTableOutput('table'))
)
)
)
shinyApp(ui, server)

最佳答案

您可以通过 input[[inputName]] 访问输入,其中 inputName 是您输入的名称(例如“Sepal.Length-7.9”)。然后你可以通过

检查所有输入
if(input[[inputName]]){
split <- strsplit(inputName, "-")[[1]]
name <- split[1]
treshold <- as.numeric(split[2])
global$filter[, inputName ==colnames(filter)] <- iris[name] == treshold
}else{
global$filter[, inputName ==colnames(filter)] = TRUE
}

您可以使用 renderUI() 创建的输入:

output$checkBoxes <- renderUI({
lapply(inputNames, function(inputName) checkboxInput(inputName, inputName, FALSE))
})

在示例中,我使用了所有数字列中的最大值。

完整代码如下:

restr <- apply(iris, 2, max)[1:4]
inputNames <- paste(names(restr), restr, sep = "-")
filter = sapply(inputNames, function(inputName) c(inputName = return(rep(TRUE, dim(iris)[1]))))


server <- function(input, output, session) {
global <- reactiveValues(filter = filter)

df <- reactive({
for(inputName in inputNames){
if(!is.null(input[[inputName]])){
isolate({
if(input[[inputName]]){
split <- strsplit(inputName, "-")[[1]]
name <- split[1]
treshold <- as.numeric(split[2])
global$filter[, inputName ==colnames(filter)] <- iris[name] == treshold
}else{
global$filter[, inputName ==colnames(filter)] = TRUE
}
})
}
}
iris[rowSums(global$filter) == 4, ]
})


output$checkBoxes <- renderUI({
lapply(inputNames, function(inputName) checkboxInput(inputName, inputName, FALSE))
})

output$table <- DT::renderDataTable(
DT::datatable(df(), options = list(searching = FALSE,pageLength = 25))
)
}
ui <- navbarPage(
title = 'Select values in two columns based on two inputs respectively',
fluidRow(
column(width = 3,
uiOutput("checkBoxes")
),
column(9,
tabPanel('Table', DT::dataTableOutput('table'))
)
)
)
shinyApp(ui, server)

关于r - 通过多列中的值在 R shiny 中有效地过滤数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53343461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com