Search code examples
rfor-loopsubstr

Change variable if a certain substring has been found (via for loop)


I would like to change the "variable" to 1, if x contains 4. This code that I have written seems not to work because after executing it the variable is still zero. I tried to include "print (i)" to see whether the for loop gets to the "4" in x, but only "1" was printed. So the for-loop seems not to make more than one run.... Could someone tell what's wrong with this code?

 x=22356478998
    variable=0
    for(i in 1:length(x)){
    if( substr(x,start=i,stop=i)=="4"){
      variable=1
      break
    }
    }

Solution

  • Just use grepl (it's in base)

    variable = as.integer(grepl("4", x))