如何从列表中删除某些元素?

时间:2021-04-12 18:43:11

标签: r list for-loop indexing

我有一个包含字符向量的列表。我想删除这些向量中等于“J”或“Co”的元素。这是我的清单:

> fh_mentioned[1:10]  
[[1]]
[1] "Co"

[[2]]
[1] "Oscar de la Renta" "Balmain"           "J"                

[[3]]
[1] "Co" "Co"

[[4]]
[1] "Christian Dior" "J"              "Dior"          

[[5]]
[1] "Christian Lacroix" "J"                

[[6]]
[1] "Louis Féraud" "Féraud"       "Burberry"     "Bally"        "Féraud"       "Féraud"      

[[7]]
[1] "J"        "Givenchy" "Givenchy" "Givenchy" "Givenchy"

[[8]]
[1] "J"

[[9]]
[1] "Vogue"             "Phi"               "Valentino"         "Alexander McQueen" "Olivier Theyskens" "Co"               

[[10]]
[1] "Yves Saint Laurent" "Co"                 "Saint Laurent"      "Co"                 "Saint Laurent"    


我试过了:

for(i in 1:length(fh_mentioned_clean)){
for(j in 1:length(fh_mentioned_clean[[i]])){
 fh_mentioned_clean[[i]] <- fh_mentioned_clean[[i]][fh_mentioned_clean[[i]][j] != "J" &
                                                      fh_mentioned_clean[[i]][j] != "Co"]
}
}

无济于事。

我还通过将那些不需要的元素设置为 NULL 来尝试在循环中使用 if 语句,但它不起作用,因为某些元素出于某种原因是字符 (0)。

0 个答案:

没有答案