使用 strsplit() 函数在 R 中对单个单词执行 break 和 next 函数

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

我正在尝试在for循环中使用break和next,我的代码如下:

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

预期输出:

c
h
a

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

预期输出:

c
h
a
t
e
r

但我对上述两个循环的输出是:

[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
> 

我也不明白为什么会收到警告消息。 我尝试了另一个数字示例:

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

输出为:

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

这里虽然向量中有两个地方有数字 5,但输出没有显示警告 "the condition has length > 1 and only the first element will be used"

如果您查看 strsplit

的输出
strsplit('chapter', '')

#[[1]]
#[1] "c" "h" "a" "p" "t" "e" "r"

这是一个长度为 1 的列表,并且该列表具有单独的元素。因此,当您在 for 循环中迭代它时,您只是在迭代第一个列表元素。您需要的是 select 第一个列表元素,然后遍历每个单独的元素。

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

如果你这样做,你将得到你需要的输出

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"