从向量中删除某些值

时间:2017-12-06 13:35:14

标签: r

我有一个带有一些字符的向量:

结构glimpse(a)

List of 5
 $ : chr [1:2] "Thai" "Restaurants"
 $ : chr [1:2] "Vietnamese" "Restaurants"
 $ : chr [1:3] "Restaurants" "Vegetarian" "Indian"
 $ : chr [1:5] "Nightlife" "Bars" "Restaurants" "Thai" ...
 $ : chr [1:4] "Asian Fusion" "Chinese" "Japanese" "Restaurants"

这是dput(a)

list(c("Thai", "Restaurants"), c("Vietnamese", "Restaurants"), 
    c("Restaurants", "Vegetarian", "Indian"), c("Nightlife", 
    "Bars", "Restaurants", "Thai", "Sports Bars"), c("Asian Fusion", 
    "Chinese", "Japanese", "Restaurants"))

我想通过排除删除一些值。例如,下面的值是应该保留在向量中的唯一值。应删除所有其他值,无需替换。

c("Chinese", "Japanese", "Sushi Bars", "Indian", "Thai", "Vietnamese", "Korean","Taiwanese", "Malaysian", "Mongolian", "Indonesian", "Laotian", "Myanmar", "Pan Asian", "Tempura", "Wok")

所以,我尝试了这篇文章中的解决方案: How to delete multiple values from a vector?

所以我做了:

rm <-  c("Chinese", "Japanese", "Sushi Bars", "Indian", "Thai", "Vietnamese", "Korean","Taiwanese", "Malaysian", "Mongolian", "Indonesian", "Laotian", "Myanmar", "Pan Asian", "Tempura", "Wok")

a [! a %in% rm]

但没有变化?! Anny Idea如何从a中删除那些不属于rm

的值

1 个答案:

答案 0 :(得分:2)

如果元素为setdiff,我们可以通过使用unique循环list元素来lapply

lapply(a,  setdiff, rm)

或者,使用%in%然后否定

lapply(a, function(x) x[!x %in% rm])