【问题标题】:Obtain index of the first element of the repeated value in a vector in R [duplicate]获取R中向量中重复值的第一个元素的索引[重复]
【发布时间】:2020-03-15 12:56:07
【问题描述】:

如何在a中,获取第一个元素的重复值的索引(第一个1的索引,第一个2,第一个3...)?

a <- c(rep(1, 3), rep(2, 2), rep(3, 1), rep(4, 2))

desired.output <- c(1, 4, 6, 7)

【问题讨论】:

标签: r vector subset


【解决方案1】:

一个选项是tapply

as.vector(tapply(seq_along(a), a, FUN = `[`, 1))
#[1] 1 4 6 7

或使用

which(!duplicated(a))

或者whichdiff

which(c(TRUE, !!diff(a)))

或者当向量不是数字时

which(c(TRUE, a[-1] != a[-length(a)]))

【讨论】:

    【解决方案2】:

    另一个选项是match

    match(unique(a), a)
    # [1] 1 4 6 7
    

    来自help('match')

    match 返回其第一个参数在第二个参数中的(第一个)匹配位置的向量。

    【讨论】:

      猜你喜欢
      • 2018-08-04
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2016-09-19
      相关资源
      最近更新 更多