【发布时间】:2018-01-18 02:07:38
【问题描述】:
我对 R 比较陌生,对 Shiny(字面意思是第一天)更加陌生。
我希望用户输入多个用逗号分隔的短语,例如 female, aged, diabetes mellitus. 我有一个数据框,其中一个变量 MH2 包含文本词。我想输出一个数据框,其中仅包含所有输入短语都存在的行。有时用户可能只输入一个短语,而其他时候 5 个。
这是我的 ui.R
library(shiny)
library(stringr)
# load dataset
load(file = "./data/all_cardiovascular_case_reports.Rdata")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput(inputId = "phrases",
label = "Please enter all the MeSH terms that you would like to search, each separated by a comma:",
value = ""),
helpText("Example: female, aged, diabetes mellitus")
),
mainPanel(DT::dataTableOutput("dataframe"))
)
)
这是我的服务器。R
library(shiny)
server <- function(input, output)
{
# where all the code will go
df <- reactive({
# counts how many phrases there are
num_phrases <- str_count(input$phrases, pattern = ", ") + 1
a <- numeric(num_phrases) # initialize vector to hold all phrases
# create vector of all entered phrases
for (i in 1:num_phrases)
{
a[i] <- noquote(strsplit(input$phrases, ", ")[[i]][1])
}
# make all phrases lowercase
a <- tolower(a)
# do exact case match so that each phrase is bound by "\\b"
a <- paste0("\\b", a, sep = "")
exact <- "\\b"
a <- paste0(a, exact, sep = "")
# subset dataframe over and over again until all phrases used
for (i in 1:num_phrases)
{
final <- final[grepl(pattern = a, x = final$MH2, ignore.case = TRUE), ]
}
return(final)
})
output$dataframe <- DT::renderDataTable({df()})
}
当我尝试运行renderText({num_phrases}) 时,我始终得到1,即使我会输入多个用逗号分隔的短语。从那时起,每当我尝试输入多个短语时,都会遇到“错误:下标越界”。但是,当我输入仅用逗号分隔的单词而不是逗号和空格(输入“女性,老年”而不是“女性,老年”)时,这个问题就消失了,但我的数据框没有正确子集。它只能子集一个短语。
请指教。
谢谢。
【问题讨论】:
标签: r dataframe text shiny textinput