根据条件包含两个相互矛盾的字符串筛选列表

时间:2017-03-22 15:11:11

标签: r list filter

my_list = list()
my_list[[1]] = c("Fast","Slow","Heavy","Light")
my_list[[2]] = c("Fast","Small","Intelligent","Light")
my_list[[3]] = c("Dumb","Slow","Heavy","Light")
my_list[[4]] = c("Slow","Intelligent","Dumb","Heavy")
my_list[[5]] = c("Heavy","Light","Intelligent","Tall")

这是我想要做的简化版本,但是我如何过滤列表以便在其中包含两个字符串(即快速和慢速,高大小,重和轻,最后,智能然后可以将它们移除以留下具有敏感载体的最终载体。

我一直试图用IF函数做到这一点,这是最合适的方式吗?

1 个答案:

答案 0 :(得分:0)

这就是你想要的:

cont_check <- function(x) {
    cont_words <- list(c("Fast", "Slow"),
                       c("Heavy", "Light"))
    found <- sum(sapply(cont_words, function (y) sum(y %in% x) == 2)) > 0 
    return(found)
}
sapply(my_list, cont_check)
# select ones
# my_list[!sapply(my_list, cont_check)]