【发布时间】:2020-05-04 21:18:50
【问题描述】:
与Tidy evaluation programming with dplyr::case_when 和Making tidyeval function inside case_when 有点相关,我想创建字符串(使用闪亮的应用程序)以便稍后在case_when 函数中解析。这是一个例子:
library(tidyverse)
# simulated shiny inputs
new_column = sym("COL_NAME")
number_of_categories = 3
col1_text = "Big"
col1_min = 7.0
col1_max = 8.0
col2_text = "Medium"
col2_min = 5.0
col2_max = 6.9
col3_text = "Small"
col3_max = 4.9
col3_min = 4.0
columninput = sym("Sepal.Length")
期望的输出
iris %>%
mutate(new_column =
case_when(
!!columninput >= col1_min & !!columninput <= col1_max ~ col1_text,
!!columninput >= col2_min & !!columninput <= col2_max ~ col2_text,
!!columninput >= col3_min & !!columninput <= col3_max ~ col3_text
)
)
因为函数之间唯一改变的是索引,我在想我们可以使用通用模式来创建一个字符串
# create single string
my_string <-function(i) {
paste0("!!", columninput, " >= col", i, "_min & ", "!!", columninput, " <= col", i, "_max ~ col", i, "_text")
}
然后重复字符串为动态案例数
mega_string <- map_chr(1:number_of_categories, ~ my_string(.x))
待办事项:
这是我无法拼凑起来的部分:使用这些字符串作为 case_when 中的参数。
# evaluate somehow?
iris %>%
mutate(
new_column = case_when(
# tidyeval mega_string?
paste(mega_string, collapse = "," )
)
)
这甚至是正确的方法吗?您将如何解决这个问题 - 任何高水平的帮助或其他方面的帮助都非常感谢!
【问题讨论】:
-
我猜你需要
eval(parseiris %>% mutate(new_column = case_when(eval(parse(text = mega_string[1])))