LB1234
LB1234

Reputation: 75

Find indices of same elements consecutively in an array in R

How can I get with this array:

a <- c(1,2,3,30,30,30,30,30,2,2,3,3,3,30)

an output with information about the indices where the same elements appear. So I would like an output of [30, 5, 4] or a different order, in which 5 is the consecutive count of 30, and 4 the index of the start of the count. Please notice that the last 30 in the array is not recognized in this output. Thanks!

Upvotes: 3

Views: 88

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389125

Using data.table -

library(data.table)

a <- c(1,2,3,30,30,30,30,30,2,2,3,3,3,30)
dt <- data.table(a, row = seq_along(a))
dt[, .(a = first(a), length = .N, row = first(row)), rleid(a)]

#   rleid  a length row
#1:     1  1      1   1
#2:     2  2      1   2
#3:     3  3      1   3
#4:     4 30      5   4
#5:     5  2      2   9
#6:     6  3      3  11
#7:     7 30      1  14

You may add |> subset(length > 1) if you need rows with only length higher than 1.

Upvotes: 1

Daman deep
Daman deep

Reputation: 631

a <- c(1,2,3,30,30,30,30,30,2,2,3,3,3,30)
vec <- unique(a)
indeX=c()
counT <- c()
count=1
valuE<- c()
for (m in 1:(length(a)-1)) {
     
    if (a[m]==a[m+1]) {
        value <- a[m]
        count=count+1
    }else{
      if (count>1) {
        indeX[m] <-m-count+1
        counT[m] <- count
        valuE[m] <- value
      }
      count=1
    }

    
    
  }


indeX <- as.vector(na.omit(indeX))
counT <- as.vector(na.omit(counT))
valuE <- as.vector(na.omit(valuE))
list=list()
for (k in 1:length(indeX)) {
  list[[k]] <-c(valuE[k],counT[k],indeX[k])
}

output

> list
[[1]]
[1] 30  5  4

[[2]]
[1] 2 2 9

[[3]]
[1]  3  3 11

Upvotes: 1

Related Questions