Count the max number of ones in a vector - r

I am doing the next task.
Suppose that I have the next vector.
(1,1,0,0,0,1,1,1,1,0,0,1,1,1,0)
I need to extract the next info.
the maximum number of sets of consecutive zeros
the mean number of consecutive zeros.
FOr instance in the previous vector
the maximum is: 3, because I have 000 00 0
Then the mean number of zeros is 2.
I am thinking in this idea because I need to do the same but with several observations. I think to implement this inside an apply function.

We could use rle for this. As there are only binary values, we could just apply the rle on the entire vector, then extract the lengths that correspond to 0 (!values - returns TRUE for 0 and FALSE others)
out <- with(rle(v1), lengths[!values])
And get the length and the mean from the output
> length(out)
[1] 3
> mean(out)
[1] 2
data
v1 <- c(1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0)

You can try another option using regmatches
> v <- c(1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0)
> s <- paste0(v, collapse = "")
> zeros <- unlist(regmatches(s, gregexpr("0+", s)))
> length(zeros)
[1] 3
> mean(nchar(zeros))
[1] 2

Related

R: randomly sample a nonzero element in a vector and replace other elements with 0

Suppose I have a vector
vec <- c(0, 1, 0, 0, 0, 1, 1, 1, 1, 2)
How do I random sample a nonzero element and turn other elements into 0?
Suppose the element sampled was vec[2], then the resulting vector would be
vec <- c(0, 1, 0, 0, 0, 0, 0, 0, 0, 0)
I know that I can sample the indice of one nonzero element by sample(which(vec != 0), 1), but I am not sure how to proceed from that. Thanks!
You can try the code below
> replace(0 * vec, sample(which(vec != 0), 1), 1)
[1] 0 0 0 0 0 0 0 1 0 0
where
which returns the indices of non-zero values
sample gives a random index
replace replaces the value to 1 at the specific index
Watch out for sample's behavior if which returns only 1 value:
> vec <- c(rep(0, 9), 1)
> sample(which(vec != 0), 1)
[1] 4
This preserves the vector value (instead of turning it to 1) and guards against vectors with only one nonzero value using rep to guarantee sample gets a vector with more than one element:
vec[-sample(rep(which(vec != 0), 2), 1)] <- 0

Calculate length of repeats along a vector in r

Is there an efficient way to calculate the length of portions of a vector that repeat a specified value?
For instance, I want to calculate the length of rainless periods along a vector of daily rainfall values:
daily_rainfall=c(15, 2, 0, 0, 0, 3, 3, 0, 0, 10)
Besides using the obvious but clunky approach of looping through the vector, what cleaner way can I get to the desired answer of
rainless_period_length=c(3, 2)
given the vector above?
R has a built-in function rle: "run-length encoding":
daily_rainfall <- c(15, 2, 0, 0, 0, 3, 3, 0, 0, 10)
runs <- rle(daily_rainfall)
rainless_period_length <- runs$lengths[runs$values == 0]
rainless_period_length
output:
[1] 3 2

R - How to plot a graph from bool values

So, I have a vector full of 1s and 0s. I need to plot a graph that starts at (0, 0) and rises by 1 for every 1 in the vector and dips by 1 for every 0 in the vector. For example if my vector is [ 1, 1, 1, 0, 1, 0, 1, 1 ] I should get something that looks like
I thought about creating another vector that would hold the sum of the first i elements of the original vector at index i (from the example: [ 1, 2, 3, 3, 4, 4, 5, 6 ]) but that would not account for the dips at 0s. Also, I cannot use loops to solve this.
I would convert the zeros to -1, add a zero at the very beginning to make sure it starts from [0,0] and then plot the cumulative sum:
#starting vec
myvec <- c(1, 1, 1, 0, 1, 0, 1, 1)
#convert 0 to -1
myvec[myvec == 0] <- -1
#add a zero at the beginning to make sure it starts from [0,0]
myvec <- c(0, myvec)
#plot cumulative sum
plot(cumsum(myvec), type = 'line')
#points(cumsum(myvec)) - if you also want the points on top of the line

R: How to find max length sequence between two values in a vector?

Let's say I want to find the longest length of consecutive numbers (excluding 0) in a sequence in R.
Example: (0,2,3,0,5) in this case it should return 2 .
The solution I came up with is as follows:
A1 <- c(1, 1, 0,1,1,1)
length =NULL
B<-rle(A1==0)
C<-B$lengths
D<-B$values
for(i in 1:length(C)){
if(D[i]==FALSE){length[i]=C[i]}
}
length <- length [!is.na(length )]
max(length)
[1] 3
How can I find the longest sequence of non-zero numbers in a vector in R?
We could use rle. A==0 output a logical index vector, rle computes the lengths and runs of values of adjacent elements that are the same for logical vector. Extract the lengths of values that are not '0' and get the max after removing the first and last elements to account for the maximum lengths of non-zero elements at the start or end of vector.
max(with(rle(A==0), lengths[-c(1, length(lengths))][
!values[-c(1, length(values))]]))
#[1] 2
Another example
A1 <- c(1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0,0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1)
max(with(rle(A1==0), lengths[-c(1, length(lengths))][
!values[-c(1, length(values))]]))
#[1] 4
Or
indx <- A1==0
max(with(rle(A1[which(indx)[1L] : tail(which(indx),1)]==0),
lengths[!values]))
#[1] 4
Update
Based on the new info, may be you can try,
A1 <- c(1, 1, 0,1,1,1)
max(with(rle(A1==0), lengths[!values]))
#[1] 3

Vectorized replacement of a subset of a vector

Simple question: I've got two vectors of 0's and 1's, a and b. The b vector has as many entries as there are 1's in a. I would like to replace the 1's in a with the entries from b. Of course I can do this in a for loop, but is there a nice vectorized way to do this?
From
a <- c(0, 1, 1, 0, 1)
b <- c(1, 0, 1)
create
c <- c(0, 1, 0, 0, 1)
This is pretty simple: a[a == 1] <- b

Resources