如何使用 dplyr 在 R 中复制 Excel 的索引匹配公式?

Cur*_*072 1 lookup indexing r excel-formula dplyr

我是 Excel 的重度用户,正在学习 R 和易于使用的 R 包 dplyr。我经常使用 Excel 的索引(...,match(...)) 公式组合从列中提取(查找)目标值。我将如何在 R 中并使用 dplyr 执行相同的操作,如下面的 Excel 插图所示?在 RI 中,我尝试复制标记为“匹配”的 G 列,该列的公式显示在其右侧突出显示为黄色并标记为“匹配列公式”的列中。

我正在使用 Excel 和配套的 R 代码来显示一系列逐步计算,以防 G 列看起来很麻烦!

在此输入图像描述

在此示例中重现起始数据帧的代码:

myData <- 
  data.frame(
    Element = c("A","A","C","A","B","B"),
    Code1 = c(0,0,0,0,1,1),
    Code2 = c(1,2,1,3,1,2),
    Code3 = c(0,0,0,0,1,2),
    Code4 = c(0,0,0,0,1.1,1.2)
  )
Run Code Online (Sandbox Code Playgroud)

nni*_*loc 5

Base R 具有match与 Excel 类似的功能。

myData$Match <- with(myData, Code4[match(Code2, Code3)] * !Code1)

myData
#-----
  Element Code1 Code2 Code3 Code4 Match
1       A     0     1     0   0.0   1.1
2       A     0     2     0   0.0   1.2
3       C     0     1     0   0.0   1.1
4       A     0     3     0   0.0    NA
5       B     1     1     1   1.1   0.0
6       B     1     2     2   1.2   0.0
Run Code Online (Sandbox Code Playgroud)

相同的想法,但使用dplyr

myData %>%
  mutate(Match = Code4[match(Code2, Code3)] * !Code1)
Run Code Online (Sandbox Code Playgroud)