闪亮的R:当模式与数据框中的给定字符向量匹配时,更新textInput

时间:2019-03-21 16:35:05

标签: r shiny dplyr

我的问题是我有一个给定的数据框,我必须搜索不同的模式。当模式与给定的字符向量匹配时,同一行但不同列的内容应更新textInput。

我创建了一个闪亮的应用程序作为示例,因为我的原始代码太大。该示例有效,但是我正在使用for循环,但我不想这样做。有谁知道更好的解决方案?有矢量功能的解决方案吗?如果有人知道dplyr解决方案,我将不胜感激。

示例:

library(shiny)

ui <- fluidPage(
textInput(inputId="wave1", label="wavelength"),
textInput(inputId="wave2", label="wavelength")
)

server <- name <- function(input,output,session) {

df <- data.frame("color" = c("red","blue","green"), "wavelength" = c("700 nm","460 nm","520 nm"))

for (i in 1:nrow(df)) {
if(grepl("lue",df$color[i],fixed=TRUE) == TRUE){updateTextInput(session, inputId="wave1", label = NULL, value = df$wavelength[i],placeholder = NULL)}
}

for (i in 1:nrow(df)) {
if(grepl("ee",df$color[i],fixed=TRUE) == TRUE){updateTextInput(session, inputId="wave2", label = NULL, value = df$wavelength[i],placeholder = NULL)}
}
}

shinyApp(ui = ui, server = server)

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以直接从grep的结果中为数据帧建立索引,而无需循环:

server <- name <- function(input,output,session) {

    df <- data.frame("color" = c("red","blue","green"), "wavelength" = c("700 nm","460 nm","520 nm"))

    updateTextInput(session, inputId="wave1", label = NULL,
                    value = df$wavelength[grep("lue", df$color, fixed=TRUE)],
                    placeholder = NULL)
    updateTextInput(session, inputId="wave2", label = NULL,
                    value = df$wavelength[grep("ee", df$color, fixed=TRUE)],
                    placeholder = NULL)
}

使用dplyr进行此操作的一种方法是:

server <- name <- function(input,output,session) {

    df <- data.frame("color" = c("red","blue","green"), "wavelength" = c("700 nm","460 nm","520 nm"))

    updateTextInput(session, inputId="wave1", label = NULL,
                    value = dplyr::filter(df, grepl("lue", color, fixed=TRUE)) %>% dplyr::pull(wavelength),
                    placeholder = NULL)
    updateTextInput(session, inputId="wave2", label = NULL,
                    value = dplyr::filter(df, grepl("ee", color, fixed=TRUE)) %>% dplyr::pull(wavelength),
                    placeholder = NULL)
}