user3581800
user3581800

Reputation: 317

How to count duplicate elements in a vector using R

I need to write a function that receives 2 arguments in R: first a number = X second a vector = V I need that this function would return the max number of the identical straight occurrences of X for example: f(6, c(7,6,6,3,7,9,3,6,6,6,8,9) should return 3

Upvotes: 0

Views: 5825

Answers (2)

Paulo E. Cardoso
Paulo E. Cardoso

Reputation: 5856

you may not need a function

dat <- c(7,6,6,3,7,9,3,6,6,6,8,9)

fmax <- function(x, vec){
  v <- rle(vec)
  max(v$lengths[v$values == x])
}
fmax(x=6, vec=dat)
[1] 3

when x in absent from dat

fmax <- function(x, vec){
  if(x %in% vec){
    v <- rle(vec)
    max(v$lengths[v$values == x])
  } else 0
}
fmax(x=20, vec=dat)
[1] 0

Upvotes: 1

Julian
Julian

Reputation: 189

r <- numeric()
j <- 0
X <- 6
for(i in 1:length(V){
j <- ifelse(v[i]==X,j+1,0)
r[i] <- j
}

max(r)

if you wanna have the maximal length for all elements in the vector:

a <- c(7,6,6,3,7,9,3,6,6,6,8,9)
b <- rle(a)
b <- data.frame(length=b$lengths, values=b$values)
aggregate(b, by=list(b$values), FUN=max)

Upvotes: 0

Related Questions