Q:

R: Simple Function with For Loop

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)
}

A:

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!

