【发布时间】:2019-09-25 07:05:10
【问题描述】:
这类似于下面的question。不过,我还需要做几个步骤:
• 按列分组 ID 和 order
• 对于df_dat 中的每个val,在df_lookup 表中查找对应的ratio,条件如下:
o If val < min(df_lookup$val), set new_ratio = min(df_lookup$ratio)
o If val > max(df_lookup$val), set new_ratio = max(df_lookup$ratio)
o If val falls within df_lookup$val range, do a simple linear interpolation
我的数据:
library(dplyr)
df_lookup <- tribble(
~ID, ~order, ~pct, ~val, ~ratio,
"batch1", 1, 1, 1, 0.2,
"batch1", 1, 10, 8, 0.5,
"batch1", 1, 25, 25, 1.2,
"batch2", 2, 1, 2, 0.1,
"batch2", 2, 10, 15, 0.75,
"batch2", 2, 25, 33, 1.5,
"batch2", 2, 50, 55, 3.2,
)
df_lookup
#> # A tibble: 7 x 5
#> ID order pct val ratio
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 batch1 1 1 1 0.2
#> 2 batch1 1 10 8 0.5
#> 3 batch1 1 25 25 1.2
#> 4 batch2 2 1 2 0.1
#> 5 batch2 2 10 15 0.75
#> 6 batch2 2 25 33 1.5
#> 7 batch2 2 50 55 3.2
df_dat <- tribble(
~order, ~ID, ~val,
1, "batch1", 0.1,
1, "batch1", 30,
1, "batch1", 2,
1, "batch1", 12,
2, "batch1", 45,
2, "batch2", 1.5,
2, "batch2", 30,
2, "batch2", 13,
2, "batch2", 60,
)
df_dat
#> # A tibble: 9 x 3
#> order ID val
#> <dbl> <chr> <dbl>
#> 1 1 batch1 0.1
#> 2 1 batch1 30
#> 3 1 batch1 2
#> 4 1 batch1 12
#> 5 2 batch1 45
#> 6 2 batch2 1.5
#> 7 2 batch2 30
#> 8 2 batch2 13
#> 9 2 batch2 60
之前的解决方案没有考虑产生错误结果的分组。
例子:
对于order = 2 和ID = batch1,new_ratio 应为 NA,因为这些条件不在查找表中。
对于order = 1、ID = batch2 和val = 30,new_ratio 不应高于1.2(最大ratio 值)。
对于order = 1、ID = batch1 和val = 2、new_ratio = 0.243,这是在 0.2 和 0.5 之间插入的 ratio 值。
任何帮助表示赞赏!
#error
df_dat %>%
group_by(ID, order) %>%
mutate(new_ratio = with(df_lookup, approx(val, ratio, val))$y)
#> Error: Column `new_ratio` must be length 4 (the group size) or one, not 7
#wrong output
df_dat %>%
group_by(ID, order) %>%
mutate(val1 = val) %>%
mutate(new_ratio = with(df_lookup, approx(val, ratio, val1))$y)
#> # A tibble: 9 x 5
#> # Groups: ID, order [3]
#> order ID val val1 new_ratio
#> <dbl> <chr> <dbl> <dbl> <dbl>
#> 1 1 batch1 0.1 0.1 NA
#> 2 1 batch1 30 30 1.39
#> 3 1 batch1 2 2 0.1
#> 4 1 batch1 12 12 0.643
#> 5 2 batch1 45 45 2.43
#> 6 2 batch2 1.5 1.5 0.15
#> 7 2 batch2 30 30 1.39
#> 8 2 batch2 13 13 0.679
#> 9 2 batch2 60 60 NA
预期输出
# A tibble: 9 x 4
order ID val new_ratio
<dbl> <chr> <dbl> <dbl>
1 1 batch1 0.1 0.2
2 1 batch1 30 1.2
3 1 batch1 2 0.243
4 1 batch1 12 0.643
5 2 batch1 45 NA
6 2 batch2 1.5 0.1
7 2 batch2 30 1.38
8 2 batch2 13 0.65
9 2 batch2 60 3.2
【问题讨论】:
-
嗨里斯。您能否添加您的预期输出(不仅仅是错误的输出)。我对您的问题陈述也不完全清楚。您之前的问题似乎完全不同。你为什么在这里使用
approx?看起来您并没有尝试插入任何内容。除非我错过了什么? -
如果
val在查找表中介于val之间,我需要在范围之间进行线性插值ratio。我按照您的建议添加了预期的输出。谢谢
标签: r dataframe dplyr data.table lookup-tables