让我们说我正在使用虹膜数据集,我想找到具有某个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)
我只想要宽度Desired_Width [i]和长度Desired_Length [i]的行
(那是第1,3和5行)
我不想使用for循环,我如何使用dplyr或'which'来做到这一点?
一种方法是使用基础R mapply
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
的purrr
也可以做到这一点
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
另一种方式来自merge
mergedf=data.frame('Sepal.Length'=Desired_Length,'Sepal.Width'=Desired_Width)
yourdf=merge(iris,mergedf,by=c('Sepal.Width','Sepal.Length'),all.y =T)