Ali
Ali

Reputation: 1013

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.

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

17`[[96]]
[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.

Upvotes: 0

Views: 183

Answers (1)

akrun
akrun

Reputation: 887691

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")

Upvotes: 1

Related Questions