将条件应用于 2 个数据框以执行计算和存储结果 - 如何自动化流程?

Applying conditions to 2 dataframes to perform calculation and store result - how to automate process?

我有两个数据框;简化版本如下所示:

df1 <- data.frame(x = c(rep(c(1:10)), rep(c(9:1))),
                  y = c(200, 183, 166, 144, 117, 80, 65, 33, 14, 0, 6, 15, 37, 65, 92, 123, 156, 182, 200))

df2 <- data.frame(WL = sample(x = 0:200, size = 19, replace = F))

对于上下文,df1 实际上表示河流横截面 (x & y),df2 表示每小时水位测量值 (WL)。

我想创建一种自动方法来计算 df2 中每个水位充满水的河道横截面积,并将该面积存储在 df2 中名为 area 的新列中。

以下代码显示了我想要实现的目标,但正如您所见,它可能会变得非常乏味,因为我的实际水位数据集非常庞大(数百行)。我将不胜感激任何有助于自动执行此过程的帮助:

# package required for calculating area of polygon
library(pracma)

# for the first observation/row in df2:
a <- ifelse(df1$y <= df2$WL[1], df1$y, 0) 
df2$area[1] <- abs(polyarea(df1$x, a)) 

# for the second observation/row in df2:
a <- ifelse(df1$y <= df2$WL[2], df1$y, 0) 
df2$area[2] <- abs(polyarea(df1$x, a))
library(tidyverse)
library(pracma)
#> 
#> Attaching package: 'pracma'
#> The following object is masked from 'package:purrr':
#> 
#>     cross

df1 <- data.frame(
  x = c(rep(c(1:10)), rep(c(9:1))),
  y = c(200, 183, 166, 144, 117, 80, 65, 33, 14, 0, 6, 15, 37, 65, 92, 123, 156, 182, 200)
)
df2 <- data.frame(WL = sample(x = 0:200, size = 19, replace = F))

df2 %>%
  as_tibble() %>%
  mutate(
    area = WL %>% map_dbl(~ {
      a <- ifelse(df1$y <= .x, df1$y, 0)
      abs(polyarea(df1$x, a))
    })
  )
#> # A tibble: 19 × 2
#>       WL  area
#>    <int> <dbl>
#>  1   128    29
#>  2   193   126
#>  3    33    26
#>  4    96    23
#>  5    26     7
#>  6    13     6
#>  7    10     6
#>  8    68    11
#>  9    93    23
#> 10   125    29
#> 11   106    23
#> 12    49    11
#> 13    12     6
#> 14   100    23
#> 15    76    11
#> 16   118    94
#> 17    20     7
#> 18    67    11
#> 19   164    41

reprex package (v2.0.0)

创建于 2022-03-02