【问题标题】:Subset dataframe in R using grep with reactive variables在 R 中使用带有反应变量的 grep 子集数据帧
【发布时间】:2016-10-23 09:50:37
【问题描述】:

我的数据框dfaplication2011、winner2012等列名

在我的 Shiny 应用程序中,我使用了 2 个反应变量:

year = reaction$year
category = reaction$category

在我的 UI 中定义。 R 为:

radioButtons("year", label = h3("Year:"),
                           choices = list("2011" = "2011", "2012" = "2012",
                                          "2013" = "2013", "2014" = "2014", 
                                          "2015" = "2015", "2016"= "2016"),selected = 1)),

 radioButtons("category", label = h3("Category"), 
                          choices = list("Aplicant" = "aplic", 
                                         "Winner" = "win", 

我的目标是使用这两个变量对我的数据框 df 进行子集化,其中包含变量名称的部分

例如,如果选择 reaction$year 2011 并且选择 reaction$category ap 我应该得到aplication2011

我正在尝试使用以下方法进行子集化:

# kindly regards to user lmo for providing this code
getMap <- function(df, reaction){
# get user selected content from getReaction function
userReaction <- getReaction(category, year)

# extract from list returned by function
yearSelect <- userReaction[["year"]]
catSelect <- userReaction[["category"]]
# extract variable
df <- df[[names(df)[grep(paste0("^", catSelect, .*, yearSelect, "$"),
                               names(df), value=TRUE)]]]

我的反应函数:

getReaction2 <- reactive({
return(list(category = input$category,
year = input$year
))

谢谢

【问题讨论】:

  • 感谢您的超快回复。我尝试了一下,但得到:

标签: r shiny subset reactive-programming


【解决方案1】:

假设reaction$category 包含变量名的开始,且reaction$year 包含变量名的完整年份,您可以使用以下表达式提取变量:

# get user selected content from getReaction function
# extract from list returned by function
yearSelect <- getReaction[["year"]]
catSelect <- getReaction[["category"]]
# extract variable
myVariable <- df[[names(df)[grep(paste0("^", catSelect, ".*", yearSelect, "$"),
                              names(df), value=TRUE)]]]

【讨论】:

  • 找不到函数 getReaction。我应该用什么代替点?
  • 在您之前的编辑中,您有一个名为 getReaction 的函数,据我了解,它返回一个长度为 2 的列表,其中包含用户选择的“年份”和“类别”。返回用户选择的函数在哪里?
  • 只需像以前一样致电getReaction2 getReaction。另外,请从您的问题中删除我的回答,或添加一个注释,说明您从我的回答中复制了它。
  • 很抱歉抄袭。我应该在 getReaction 括号中添加什么而不是点?
  • 请检查您的正则表达式。它说有些引号是不必要的
猜你喜欢
  • 2018-08-25
  • 2013-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多