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

标签 r for-loop

我想编写一个简单的循环,检查 a 中是否存在 a.sub 的任何元素,然后提取该元素并打印其值

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,因为 a.suba 中都存在 3?

最佳答案

当我们使用if/else时,需要考虑的一件事是条件生成的输出的长度。 if/else 期望长度为 1 的逻辑输出,并且未进行矢量化。这里的问题是检查另一个向量中是否存在一个向量的任何元素

if(any(a.sub %in% a)) print(a.sub[a.sub %in% a]) else print("No element present")
#[1] 3

关于r - 检查某个元素是否存在于另一个向量中并打印其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52099044/

相关文章:

linux - 错误 : gdal-config not found while installing R dependent packages whereas gdal is installed

r - 为什么函数的 dplyr::mutate 只影响第一行而不影响其余行

删除向量中属于另一个向量子串的元素

c++ - C 或 C++ 中的 Csing for

python - python 中嵌套循环中的嵌套打印

r - 自动删除文件/文件夹

r - 对多个 AutoTuning 实例进行基准测试

vb.net - VB 中的循环

javascript - 每次用户填写 3 个输入时,如何在数组中自动创建一个对象?

r - 列表列表中元素替换的慢循环