让我们说我正在使用虹膜数据集,我想找到每个具有特定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或'哪一个'?
答案 0 :(得分:3)
一种方法是使用基数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
答案 1 :(得分:1)
从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)