修改%in%运算符以在列表中查找对象 [英] Modify %in% operator to find an object in a list
本文介绍了修改%in%运算符以在列表中查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须修改%in%
运算符,该运算符将在列表中找到对象.
I have to modify %in%
operator which will find an objects in a list.
我有一个列表:
list1 <- list(c(5,6), 6, list(2, c(5, 6)), "string")
未修改的%in%
运算符:
c(5,6) %in% list1
6 %in% list1
2 %in% list1
list(2, c(5,6)) %in% list1
将返回:
TRUE
TRUE
FALSE
FALSE
但对于list(2, c(5,6)) %in% list1
,我需要它返回TRUE
,因为它是此列表的元素.
but for list(2, c(5,6)) %in% list1
I need it to return TRUE
as it is an element of this list.
我必须在不使用循环的情况下实现它,并且陷入困境.
I have to implement it without using loops and I got stuck.
推荐答案
purrr::has_element
应该会给您您想要的东西:
purrr::has_element
should give you what you want:
purrr::has_element(list1, c(5,6))
#[1] TRUE
purrr::has_element(list1, 6)
#[1] TRUE
purrr::has_element(list1, 2)
#[1] FALSE
purrr::has_element(list1, list(2, c(5,6)))
#[1] TRUE
您还可以编写自己的infix函数,该函数环绕该函数,其作用类似于%in%
:
You could also write your own infix function that wraps around this function and works like %in%
:
`%in2%` <- function(lhs, rhs) purrr::has_element(rhs, lhs)
c(5,6) %in2% list1
#[1] TRUE
6 %in2% list1
#[1] TRUE
2 %in2% list1
#[1] FALSE
list(2, c(5,6)) %in2% list1
#[1] TRUE
这篇关于修改%in%运算符以在列表中查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文