0

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

user3581800
  • 317
  • 2
  • 5
  • 16

2 Answers2

1

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
Paulo E. Cardoso
  • 5,778
  • 32
  • 42
0
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)
Julian
  • 189
  • 1
  • 6
  • thanks!however, the issue is that I need a general function that would do so, and not specifically with the digit 6 or any specific vector. – user3581800 Apr 28 '14 at 15:14