【问题标题】:Using Shiny input variable within dplyr chain在 dplyr 链中使用 Shiny 输入变量
【发布时间】:2018-02-03 01:17:08
【问题描述】:

我的输入单选按钮允许用户过滤多个功能,包括“语音”、“格式”、“设备类型”。

这是一个带有硬编码值的数据框,使用“语音”选项允许我的 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,某些操作不起作用。

我尝试通过将硬编码示例“Voice”切换为 input$breakdown 来逐步完成初始 df,但未能隔离问题。

我应该如何让 df 组合使用输入变量 input$breakdown,因为我知道带有“语音”的硬编码版本确实有效?

【问题讨论】:

  • 不要使用mutate_ 试试mutate(the_breakdown = !! rlang::sym(the_breakdown)) 请展示一个可重现的小例子
  • @akrun 感谢这确实适用于变异部分。我在 rename() 部分尝试了相同的方法,但没有成功。收到错误消息unexpected '=' 118: rename(date = Var1, 119: !! rlang::sym(the_breakdown) =
  • 在此期间,我使用了setNames(c("date", the_breakdown)),但希望能够使用 rename() 并了解将来如何克服这个问题
  • 你可以使用rename_at
  • 或者如果你只需要rename 那么df1 %&gt;% rename(digitnew := !!rlang::sym(the_breakdown)) %&gt;% names %&gt;% first [1] "digitnew"

标签: r shiny


【解决方案1】:

我们可以将renamemutate 与来自rlangsym 一起使用

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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2014-12-30
    • 2015-09-08
    • 1970-01-01
    • 2018-06-17
    • 2021-04-14
    相关资源
    最近更新 更多