首页 > 解决方案 > 在 Shiny 中启用数据帧的某些部分的关键字?

问题描述

一个数据框有 5 列,其中之一是这样的:

colors
12 red
12 red
34 grey
32 cyan
14 black

我只想返回列颜色中包含红色字样的数据。所有的列。

代码:

df[df$colors %like% "red", ]

我正在制作一个闪亮的应用程序,它将从某个位置(固定)读取 csv。用户将无法更改读取的文件,只能通过源代码。

在此人开始使用该应用程序之前,我想询问一个类似密码的词。根据他使用的词,他们可以使用部分数据集。

例如,如果他们通过这个词:

pass1 

只有df[df$colors %like% "red", ]他们才能看到。

我该如何处理?

标签: rshiny

解决方案


您可以使用键值对。在 R 中,这是通过定义两个向量来完成的——一个作为键向量,另一个作为值向量,并使用 names() 来“命名”值。这是基于您提供的示例数据的解决方案:

library(shiny)
library(dplyr)

# Dummy data
val <- c(12, 12, 34, 32, 14)
color <- c("red", "red", "grey", "cyan", "black")
foo <- cbind.data.frame(val, color)

ui =  fluidPage(
  textInput("pswd", "Enter password:"),
  tableOutput("table1")
)

server = function(input, output, session) {

  # Keys
  passwords <- c("pass1", "pass2", "pass3", "pass4") #....and so on
  # Values
  colors.filter <- c("red", "grey", "cyan", "black") #....and so on
  # Assign names to make key-value pairs
  names(colors.filter) <- passwords

  # Subset data - select only corresponding value for input key
  bar <- reactive({
    filter(foo, color %like% colors.filter[input$pswd])
  })

  output$table1 <- renderTable({
    bar()
  })

} 

shinyApp(ui,server)

推荐阅读