Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding vector elements with a length longer than 1 in R

Tags:

r

I have a vector like this

c(0,1,2,0,0,2,2,2,2,2,2,1,0,1,2,2,2,2,2,1)

I would like to find the position where a series of at least three consecutive 2's, c(2,2,2), starts and if it is interupted I would like to find the next first postion.

The return vector should look something like this:

FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE

I have tried match and several other functions but without success

like image 204
Mart Avatar asked May 29 '13 02:05

Mart


People also ask

What does length () in R do?

length() function in R Programming Language is used to get or set the length of a vector (list) or other objects.

How do you find the length of each element in a vector in R?

In R programming language, to find the length of every elements in a list, the function lengths() can be used. This function loops over x and returns a compatible vector containing the length of each element in x.

How do I create a specific length vector in R?

To create a vector of specified data type and length in R we make use of function vector(). vector() function is also used to create empty vector.


2 Answers

Here is one way:

x <- c(0,1,2,0,0,2,2,2,2,2,2,1,0,1,2,2,2,2,2,1)
a <- rle(x)
z <- rep(FALSE, length(x))
z[sequence(a$lengths) == 1] <- a$lengths >= 2 & a$values == 2
z
#  [1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
# [11] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
like image 149
flodel Avatar answered Sep 19 '22 12:09

flodel


r <- rle(x)
# Which entries are true in the result:

w <- (cumsum(r$length)[r$values==2] - (r$length[r$values==2]-1))[r$length[r$values==2]>2]
result <- logical(length(x))
result[w] <- T
result
##  [1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
## [17] FALSE FALSE FALSE FALSE
like image 29
Matthew Lundberg Avatar answered Sep 21 '22 12:09

Matthew Lundberg