Search code examples
rbreakstrsplit

break and next functions in R on a single word using strsplit() function


I am trying to use break and next in for loop, my code is as below:

for(i in strsplit('chapter', '')){
  if(i == 'p'){
    break
  }
  print(i)
}

Expected output:

c
h
a

for(i in strsplit('chapter', '')){
  if(i == 'p'){
    next
  }
  print(i)
}

Expected Output:

c
h
a
t
e
r

But my output for both of above loops is:

[1] "c" "h" "a" "p" "t" "e" "r"
Warning message:
In if (i == "p") { :
  the condition has length > 1 and only the first element will be used
> 

Also I don't understand the Warning message, why I am getting that. I tried another numeric example:

x <- c(1,5,2,6,8,5,9,1)
for (val in x) {
  if (val == 5){
    next
  }
  print(val)
}

Output is:

[1] 1
[1] 2
[1] 6
[1] 8
[1] 9
[1] 1
> 

Here although number 5 is there in two places in the vector, the output doesn't show the warning "the condition has length > 1 and only the first element will be used"


Solution

  • If you look at the output of strsplit

    strsplit('chapter', '')
    
    #[[1]]
    #[1] "c" "h" "a" "p" "t" "e" "r"
    

    It is a list of length 1 and that list has individual elements. So when you iterate over it in a for loop you are just iterating over 1st list element. What you needed is to select the first list element and then iterate over each individual elements.

    strsplit('chapter', '')[[1]]
    #[1] "c" "h" "a" "p" "t" "e" "r"
    

    You will get your required output if you do

    for(i in strsplit('chapter', '')[[1]]){
       if(i == 'p'){
          break
       }
       print(i)
    }
    
    #[1] "c"
    #[1] "h"
    #[1] "a"
    
    for(i in strsplit('chapter', '')[[1]]){
      if(i == 'p'){
         next
       }
      print(i)
    }
    
    #[1] "c"
    #[1] "h"
    #[1] "a"
    #[1] "t"
    #[1] "e"
    #[1] "r"