R:如何在不使用循环的情况下找到按唯一向量排序的所有重复向量值的索引?

R: how to find index of all repetition vector values order by unique vector without using loop?

我有一个这样的整数向量:

a <- c(2,3,4,1,2,1,3,5,6,3,2)
values<-c(1,2,3,4,5,6)

我想为我的向量中的每个唯一值(正在排序的唯一值)列出它们出现的位置。我想要的输出:

rep_indx<-data.frame(c(4,6),c(1,5,11),c(2,7,10),c(3),c(8),c(9))

您可以使用 sapply 执行此操作。 sort 函数确保您需要的顺序。

sapply(sort(unique(a)), function(x) which(a %in% x))
#### [[1]]
#### [1] 4 6
#### 
#### [[2]]
#### [1]  1  5 11
#### ...

它会生成一个列表,给出你重复的索引。它不能是 data.frame,因为 data.frame 需要具有相同长度的列。

sort(unique(a)) 正是您的 vector 变量。

注意:您还可以使用 lapply 强制输出为列表。使用 sapply,您会得到一个列表,除非重复次数总是相同,否则输出将是一个矩阵...因此,您的选择!

您可以使用 lapply 函数来 return 带有索引的列表。

lapply(values, function (x) which(a == x))

split 非常适合这里,returns a:

中每个唯一值的索引列表
indList <- split(seq_along(a), a)
indList
# $`1`
# [1] 4 6
# 
# $`2`
# [1]  1  5 11
# 
# $`3`
# [1]  2  7 10
# 
# $`4`
# [1] 3
# 
# $`5`
# [1] 8
# 
# $`6`
# [1] 9

并且您可以通过将值作为字符传递来访问索引,即:

indList[["1"]]
# [1] 4 6

也许这也行

order(match(a, values))
#[1]  4  6  1  5 11  2  7 10  3  8  9