R ifelse pumping out NAs

Viewed 64

I'm trying to count "chunks" of similar consecutive numbers in a vector. But my code is spitting back "NA"s when I expect it to be putting in either a "1" or a "0"

x <- c(1,1,0,1,1,1,0,0,1)
y <- c(0)

turing <- function(x){
  y <- c(0)
  for (i in length(x)){
    ifelse(isTRUE(x[i] == x[i+1]), y[i]<-0, y[i]<-1)
  }
  y
}
turing(x)

This spits out [1] 0 NA NA NA NA NA NA NA 1

EDIT: The following seems to work fine:

turing <- function(x){
  y <-  numeric(length(x))
  for (i in seq_along(x)){
    ifelse(isTRUE(x[i] == x[i+1]), y[i] <-0 , y[i] <- 1)
  }
  y
}

As it spits out 0 1 1 0 0 1 0 1 1 Thanks!

3 Answers

If we need a count sequence, can use rleid from data.table

library(data.table)
rleid(x)

or with rle from base R

with(rle(x), rep(seq_along(values), lengths))

With OP's code, can pre-assign 'y' as a vector with length equal to that of length of x, then loop over the sequence of 'x' (instead of 'length' as length is just a single number), then do if/else (ifelse is vectorized option and as we are doing this in a loop if/else is only needed)

turing <- function(x){
    y <-  numeric(length(x))
    for (i in seq_along(x)){
    if(i < length(x)) {
      if(x[i] == x[i+1]) {
        y[i]<-0
        } else y[i]<-1
    }}
    y[length(y)] <- 1

    y
  }

turing(x)
#[1] 0 1 1 0 0 1 0 1 1  

Perhaps this works for you:

x <- c(1,1,0,1,1,1,0,0,1)
y <- c(0)

turing <- function(x){
  j<- 1
  for (i in x){
    y[j] <- ifelse((x[j] == x[j+1]), 0, 1)
    j <- j+1
  }
  y
}
turing(x)

Thanks for pointing out the previous mistake @akrun

I will add one more answer since all previous answers have missed that cool thing with the function ifelse is that i works on the whole vector so you dont need any for loop and index

turing <- function(x){
  ifelse(x[1:length(x)-1] == x[2:length(x)], 0,1)
}
turing(x)

you can also use the function lead from the dplyr package to have it a bit more clean

ifelse(x == dplyr::lead(x), 0,1)

Hope this helps!!

Related