user2105469
user2105469

Reputation: 1433

conditional list indexing in R

The output of strsplit() can be the following:

list( c("a","b") , character(0) , c("a","b") )

or, if assigning the expression to lst:

> lst
[[1]]
[1] "a" "b"

[[2]]
character(0)

[[3]]
[1] "a" "b"

What is the vectorized way to replace the character(0) entry? I'm trying to avoid the following:

for( i in seq(1,length(lst)) ){
  if (length(lst[[i]]) == 0) {
    lst[[i]] <- "nothing"
  }
}

Upvotes: 1

Views: 81

Answers (1)

Jthorpe
Jthorpe

Reputation: 10167

How about:

lst[sapply(lst,identical,character(0))] <- 'nothing'

Upvotes: 3

Related Questions