首页 > 解决方案 > 如何在 R 中进行成对列表匹配?

问题描述

假设我正在使用 iris 数据集,并且我想找到具有特定 Sepal.Width 和 Petal.Length 的每个值的索引(或只是子集)。

Desired_Width = c(3.5, 3.2, 3.6)
Desired_Length = c(1.4, 1.3, 1.4)

我不想混搭,就像我做以下事情一样:

Desired_index = which(iris$Sepal.Width %in% Desired_Width &
                      iris$Petal.Length %in% Desired_Length)

我只想要 Widths Desired_Width[ i ] 和 Lengths Desired_Length[ i ] 的行

(即第 1、3 和 5 行。)

我不想使用 for 循环,我将如何使用 dplyr 或“which”来做到这一点?

标签: rdplyr

解决方案


一种方法是使用基础 Rmapply

mapply(function(x, y) which(iris$Sepal.Width == x & iris$Petal.Length == y),
                      Desired_Width, Desired_Length)


#     [,1] [,2] [,3]
#[1,]    1    3    5
#[2,]   18   43   38

请注意,输出中有两行,因为有两个条目满足条件。例如,对于第一个条目,我们可以检查第 1 行和第 18 行是否具有相同Sepal.WidthPetal.Length值。

iris[c(1, 18), ]
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1           5.1         3.5          1.4         0.2  setosa
#18          5.1         3.5          1.4         0.3  setosa

同样可以使用map2frompurrr

purrr::map2(Desired_Width, Desired_Length, 
    ~which(iris$Sepal.Width == .x & iris$Petal.Length == .y))


#[[1]]
#[1]  1 18

#[[2]]
#[1]  3 43

#[[3]]
#[1]  5 38

推荐阅读