r - 如何在 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”来做到这一点?
解决方案
一种方法是使用基础 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.Width
的Petal.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
同样可以使用map2
frompurrr
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
推荐阅读
- json - 如何以角度显示对象?
- docker - 如何将 PEM 证书从 ConfigMap 动态添加到 OpenShift 中的 Java cacerts?
- python - Django过滤最新文件
- java - Android 应用将 HED 与 OpenCV 和深度学习 (Java) 结合使用
- javascript - 如何测试一个 thunk 是否已通过调度?
- php - 在 WooCommerce 管理产品列表中为“每页的项目数”设置默认值
- javascript - 如何使用 react-virualized 在表格上实现无限滚动?
- react-native - 添加条件以允许扫描
- android - 是否可以在没有预览和用户交互的情况下拍照?
- python - 有没有办法强制任何函数在 Python 中不冗长?