【发布时间】:2020-06-25 18:02:13
【问题描述】:
我有一个数据集dt,其中有一列名为x,其中包含数字和意外值。我的目标是使用dplyr::filter() 函数从基于x 的值的查找表中检索一个值,而不清理x(因为存在意外值)。如果在查找表中找不到条件语句,dplyr::filter() 返回一个空 tibble,我想将此输出替换为 0.0 的值作为数组。
这是我的代码示例:
dt <- tibble(x = c(0, -1, 0.5))
lookup_table <- tibble(
lower_bound = c(0, 0.2, 0.5),
upper_bound = c(0.2, 0.5, 1000000),
output = c(0.1, 0.2, 0.3)
)
y <- lookup_table %>% filter(lower_bound <= dt$x, upper_bound > dt$x) %>% select(output) %>% pull() %>% if_else(length() != 0, lookup_table %>% filter(lower_bound <= dt$x, upper_bound > dt$x) %>% select(output) %>% pull(), 0.0)
y
>>> [1] 0.1 0.0 0.3 # Expected output
谢谢你,
约翰
编辑:请注意dt 和查找表的行数不一定相同。
【问题讨论】: