Reputation: 817
I have an elementary question that I sadly cannot figure out. I have a set of numeric vector of 1s and 0s that are stored in the return
variable below and whose sums are stored in the totals
variable. I would like to check each of these individual vectors to see if there were consecutive zeroes in the result, and then return the total number of times this occurred. However, I'm quite rusty and/or bad at for loops/functions and cannot get this result. My latest attempt is below. Any suggestions are welcome - appreciate the help.
set.seed(1)
return = ifelse(runif(10) <= 0.6, 1, 0)
totals = sapply(1:10, function (x) sum(ifelse(runif(10)<=0.6,1,0)))
sums = function (x) {
g = 0
for (i in 1:length(x)-1) {
sum(ifelse (x[i]+x[i+1]=0,1,0))
}
return (g)
}
Upvotes: 1
Views: 55
Reputation: 887158
If we are looking for the number of times consecutive 0's occur (i.e. greater than 1) and its length, then use rle
with(rle(return), lengths[values==0 & lengths > 1])
#[1] 4
The return
vector is
return
#[1] 1 1 1 0 1 0 0 0 0 1
Now, we can see the 4
consecutive number of 0's. Just to show that the answer matches the initial vector
A for
loop (incorrect answer just for the sake of answering)
sums <- function (x) {
g <- 0
for (i in tail(seq_along(x), -1)) {
if(x[i-1]==0 & x[i]==0) {
g <- g+1
}
}
g
}
sums(return)
Upvotes: 1
Reputation: 25385
Although this is not the most efficient way to do so (see akrun's answer), we can get your for loop to work:
sums=function (x)
{
g=0
# watch your brackets! 1:3-1 returns c(0,1,2), not c(1,2)!
for (i in 1:length(x)-1)
{
# To test for equality, use a double ==, rather than a single.
# also, your 'g' variable is not updated, which is what you want to do.
sum(ifelse (x[i]+x[i+1]=0,1,0))
}
return (g)
}
Corrected:
sums <-function(x)
{
g=0
for (i in 1:(length(x)-1))
{
g= g+ifelse(x[i]+x[i+1]==0,1,0)
}
return (g)
}
You can call your function by:
return=ifelse(runif(10)<=0.6,1,0)
sums(return)
Or to generate ten vectors with random 1's and 0's, and apply your function to them, you could do:
totals = lapply(1:10, function (x) ifelse(runif(10) <= 0.6, 1, 0))
sapply(totals,sums)
Hope this helps!
Upvotes: 1