Ryan Erwin
Ryan Erwin

Reputation: 817

Remove Blank Subitems of List

Hi I am trying to remove blank sub-items of a list:

l <- list(c(1:3), c(1,"",3))

and the output should look like

[[1]]
[1] 1 2 3
[[2]]
[1] 1 3

I've tried the following with no success:

l[lapply(l, function(x) x != "")]

and the I get the error:

Error in l[lapply(l, function(x) x != "")] : 
 invalid subscript type 'list'

Seems simple, but I have not found the solution here on SO.

Upvotes: 0

Views: 43

Answers (1)

talat
talat

Reputation: 70336

Loop over the list, and subset each vector to remove blank elements:

lapply(l, function(x) as.numeric(x[x!= ""]))
#[[1]]
#[1] 1 2 3
#
#[[2]]
#[1] 1 3

I added as.numeric which seemed reasonable.

Upvotes: 5

Related Questions