如何根据另一个查询表/数据帧自动为一个数据帧插入值? [英] How to automatically interpolate values for one data frame based on another lookup table/data frame?

查看:115
本文介绍了如何根据另一个查询表/数据帧自动为一个数据帧插入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框和一个查询表。我想将 df_dat $ value df_lookup $ threshold 进行比较。
如果处于阈值范围内,则创建一个新列 transfer df_dat 中,以便其值是从 transfer 列线性插值的
df_lookup

I have one data frame and one look up table. What I want is to compare df_dat$value with df_lookup$threshold. If the value falls into threshold range, then create a new column transfer in df_dat so that its values are linearly interpolated from the transfer column in df_lookup

library(dplyr)

df_lookup <- tribble(
  ~threshold, ~transfer,
  0,   0,
  100,   15,
  200,   35
)
df_lookup
#> # A tibble: 3 x 2
#>   threshold transfer
#>       <dbl>    <dbl>
#> 1         0        0
#> 2       100       15
#> 3       200       35

df_dat <- tribble(
  ~date, ~value,
  "2009-01-01", 0,
  "2009-01-02", 30,
  "2009-01-06", 105,
  "2009-01-09", 150
)
df_dat
#> # A tibble: 4 x 2
#>   date       value
#>   <chr>      <dbl>
#> 1 2009-01-01     0
#> 2 2009-01-02    30
#> 3 2009-01-06   105
#> 4 2009-01-09   150

我可以像这样手动操作,但是想知道是否有自动 df_lookup 表中的值的方法?谢谢。

I can manually do it like this but wondering if there is an automatic way based on the values from the df_lookup table? Thank you.

df_dat %>% 
  mutate(transfer = case_when(value > 0 & value < 100 ~ 0 + (value - 0)*(15 - 0)/(100 - 0),
                              value >= 100 & value < 200 ~ 15 + (value - 100)*(35 - 15)/(200 - 100),
                              TRUE ~ 0)
  )
#> # A tibble: 4 x 3
#>   date       value transfer
#>   <chr>      <dbl>    <dbl>
#> 1 2009-01-01     0      0  
#> 2 2009-01-02    30      4.5
#> 3 2009-01-06   105     16  
#> 4 2009-01-09   150     25


推荐答案

您可以使用大约

df_dat %>% mutate(transfer = with(df_lookup, approx(threshold, transfer, value))$y)
## A tibble: 4 x 3
#  date       value transfer
#  <chr>      <dbl>    <dbl>
#1 2009-01-01     0      0
#2 2009-01-02    30      4.5
#3 2009-01-06   105     16
#4 2009-01-09   150     25

这篇关于如何根据另一个查询表/数据帧自动为一个数据帧插入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆