在dplyr链中使用Shiny输入变量

时间:2018-02-03 01:17:08

标签: r shiny

我的输入单选按钮允许用户可以过滤的多种功能,包括"语音","格式"," DeviceType"。

这是一个带有硬编码值的数据框,使用" Voice"允许我的Shiny应用程序在使用时运行的选项:

combinations <- reactive({
  expand.grid(unique(combined_data$date),
                            unique(combined_data$Voice)) %>%
  rename_("date" = "Var1",
         "Voice" = "Var2") %>%
 mutate_("Voice" = as.character("Voice"))
})

我试图转换组合以使用输入变量:

combinations <- reactive({
  the_breakdown <- input$breakdown
  expand.grid(unique(combined_data$date),
                            unique(combined_data[[input$breakdown]])) %>%
  rename_("date" = "Var1",
         the_breakdown = "Var2") %>%
 mutate_(the_breakdown = as.character(the_breakdown))
})

这在我的代码中稍后会出现错误,现在I'm having a hard time debugging it。但是,很明显,我尝试制作反应式数据框combinations()使用变量input$breakdown,但某些功能不起作用。

我尝试通过切换硬编码示例&#34; Voice&#34;逐步完成初始df。输入$细分但未能解决问题。

我应该如何让df组合使用输入变量input$breakdown,因为我知道带有&#34; Voice&#34;的硬编码版本。有用吗?

1 个答案:

答案 0 :(得分:1)

我们可以使用renamemutate sym来自rlang

combinations <- reactive({
 the_breakdown <- input$breakdown
  expand.grid(unique(combined_data$date),
                         unique(combined_data[[input$breakdown]])) %>%
  rename(date = Var1,
         !! the_breakdown := Var2) %>%
  mutate(!! the_breakdown :=  as.character(!! rlang::sym(the_breakdown)))
})

使用一个可重复的小例子

the_breakdown <- 'digitnew'
df1 %>%
  rename(!!the_breakdown := digit, s9 = s3)  %>% #rename
  mutate(!! the_breakdown :=  as.character(!! rlang::sym(the_breakdown)))  %>% #transform
  str # get the structure
# 'data.frame':   4 obs. of  8 variables:
# $ digitnew: chr  "0" "1" "2" "3"  #####
# $ s1      : int  1 0 1 1
# $ s2      : int  1 0 0 0
# $ s9      : int  1 1 1 1
# $ s4      : int  1 0 0 1
# $ s5      : int  1 0 1 0
# $ s6      : int  1 1 0 1
# $ s7      : int  0 0 0 1

数据

df1 <- structure(list(digit = 0:3, s1 = c(1L, 0L, 1L, 1L), s2 = c(1L, 
 0L, 0L, 0L), s3 = c(1L, 1L, 1L, 1L), s4 = c(1L, 0L, 0L, 1L), 
s5 = c(1L, 0L, 1L, 0L), s6 = c(1L, 1L, 0L, 1L), s7 = c(0L, 
0L, 0L, 1L)), .Names = c("digit", "s1", "s2", "s3", "s4",  
 "s5", "s6", "s7"), row.names = c("1", "2", "3", "4"), class = "data.frame")