Ali Ali - 1 year ago 96
R Question

Removing empty words in a list in R

I have a long list of words, some of which are empty strings. This is part of the list.

[1] "while" "" "however" "" "the" "right" "is" "unsettled"
[9] "" "we" "have" "avoided" "changing" "the" "state"

[1] "of" "things" "by" "taking" "new" "posts"
[7] "or" "strengthening" "ourselves" "in" "the" "disputed"

I'm trying to get rid of the empty strings in each element of the list. I don't know how to do this using regular expressions, and can't figure why the following lapply doesn't work either:

new_list = lapply(list, function(x) x = x[x != ""])

Can you help correct the code? Also, do you know how to use regexp for that? Thanks.

Answer Source

We can use grep

lapply(list, function(x) lapply(x, grep, pattern = "^$", value = TRUE, invert = TRUE))

Or as @thelatemail mentioned the recursive apply (rapply) can be used

rapply(list, grep, pattern = "^$", value = TRUE, invert= TRUE, how = "list")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download