查找唯一元素的向量索引

时间:2018-07-05 02:34:16

标签: r vector

set.seed(2)
vec <- sample(seq(3), 10, replace=T)
inverse_indices <- c(1,2,3,1,2,2,1,2,3,3)
identical(unique(vec)[inverse_indices], vec) #True

np.unique中,如果将return_inverse设置为True,我们可以获得可用于重建数组的唯一数组的索引。

如何获得R中的inverse_indices

1 个答案:

答案 0 :(得分:0)

一个选项是[{"qty": 12, "fail": 0, "pass": 12}, {"qty": 12, "fail": 0, "pass": 12}, {"qty": 12, "fail": 1, "pass": 11}, {"qty": 12, "fail": 1, "pass": 11}, {"qty": 12, "fail": 1, "pass": 11}, {"qty": 12, "fail": 2, "pass": 10}] ,其match值为'vec'

unique

或者将另一个选项转换为new_indices <- match(vec, unique(vec)) all.equal(new_indices, inverse_indices) #[1] TRUE ,然后将其强制转换为factor

integer