我有一个清单:
name_lst <- list(one = c("John", "Paul", "Ringo", "Kramer"), two = c("Jerry", "Kramer", "George", "Elaine"))
我想从中删除“ Kramer” name_lst[[SOME_VECTOR]]
,但返回列表的其余部分。希望输出为:
name_lst $one [1] "John" "Paul" "Ringo" $two [1] "Jerry" "Kramer" "George" "Elaine"
理想情况下,我可以删除整个名称,而不仅仅是“ Kramer”(例如,! %in% c("George", "Kramer")
。
name_lst[name_lst[1] != "Kramer"] name_lst[name_lst[[1]] != "Kramer"] name_lst[name_lst$one != "Kramer"] name_lst[!(name_lst$one %in% "Kramer")] name_lst[[name_lst[1] != "Kramer"]] name_lst[[name_lst[[1]] != "Kramer"]] name_lst[[name_lst$one != "Kramer"]] name_lst[[!(name_lst$one %in% "Kramer")]]
这些都返回错误或相同列表,而没有任何更改。
您可以指定要在其中查找的元素,然后过滤并重新分配给该特定列表元素:
name_lst[["one"]] <- name_lst[["one"]][!(name_lst[["one"]] %in% c("Kramer", "SomeoneElse"))] name_lst #$one #[1] "John" "Paul" "Ringo" # #$two #[1] "Jerry" "Kramer" "George" "Elaine"
如注释中所述,如果您不想执行重新分配但想获取一个新对象,则使用方法purrr::map_if
是一种。
library(purrr) NEW_NAME <- name_lst %>% map_if(.p = names(.) == "two", ~ .[!(. %in% c("Kramer", "SomeoneElse"))]) # OR, without pipes: NEW_NAME <- map_if(name_lst, names(name_lst) == "two", ~ .x[!(.x %in% c("Kramer", "SomeoneElse"))])