代码之家  ›  专栏  ›  技术社区  ›  89_Simple

检查元素是否存在于另一个向量中并打印其值

  •  2
  • 89_Simple  · 技术社区  · 8 年前

    我想写一个简单的循环来检查 a.sub 存在于 a ,然后提取该元素并打印其值

    a.sub <- c(22,3)
    a <- seq(1: 10)
    
    if(a.sub %in% a){
    
      present <-  a.sub[a.sub %in% a] # this extract the value in `a.sub` which is present in `a` 
      print(present)
    
    } else {
    
      print("no element is present")
    }
    
    "no element is present"
    Warning message:
      In if (a.sub %in% a) { :
          the condition has length > 1 and only the first element will be used
    

    3 因为两者中都有3 a、 子 ?

    2 回复  |  直到 8 年前
        1
  •  2
  •   akrun    8 年前

    if/else ,需要考虑的一点是条件生成的输出的长度。这个 如果/否则 需要长度为1的逻辑输出,但未矢量化。在这里,问题是检查是否有 any 一个向量在另一个向量中的元素

    if(any(a.sub %in% a)) print(a.sub[a.sub %in% a]) else print("No element present")
    #[1] 3
    
        2
  •  2
  •   SmitM    8 年前

    if ifelse 这样地:

    ifelse(a.sub %in% a, a.sub, "Not found")