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
Asked
Active
Viewed 5,716 times
0
-
2`max(rle(your.vector)$lengths)` should suffice. – Carl Witthoft Apr 28 '14 at 14:55
-
I think this would ignore the x which I need to choose for "running" on the vector – user3581800 Apr 28 '14 at 15:44
-
Sorry- I skimmed the question and thought you just wanted the max length regardless of value. The answers provided include the ability to report for each value in the vector. – Carl Witthoft Apr 28 '14 at 15:57
2 Answers
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
-
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
-
this is a general function. change dat and x accordingly to get the desired output. Am I wrong? – Paulo E. Cardoso Apr 28 '14 at 15:18
-
and if the X is not part of the vector, how will force it to return "0" – user3581800 Apr 28 '14 at 15:33
-
-
-
See if the answer is enough for your case but yes. In any case you should provide as much information as possible to enhance the change to receive better answers. – Paulo E. Cardoso Apr 28 '14 at 15: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