【问题标题】:break and next functions in R on a single word using strsplit() function使用 strsplit() 函数在 R 中对单个单词进行 break 和 next 函数
【发布时间】:2019-06-26 21:28:06
【问题描述】:

我正在尝试在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 在向量中的两个位置存在,但输出未显示警告“条件的长度 > 1 并且仅使用第一个元素”

【问题讨论】:

    标签: r break next strsplit


    【解决方案1】:

    如果你查看strsplit的输出

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

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

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-06
      • 2020-08-29
      • 1970-01-01
      • 2017-02-07
      • 2020-03-16
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多