NBK
NBK

Reputation: 905

r - dealing with NAs when using lapply to select sublist elements by position

I have a list of vectors, some of which are NA. I need to use lapply to select the second-to-last element of each vector. The problem is that NAs have length 1, so I cannot access their second-to-last element.

MyList <- list(a=c("a","b","c"),b=NA,c=c("d","e","f"))
VectorFromList <- unlist(lapply(MyList, function(x) return(x[length(x)-1])))
VectorFromList
  a   c 
"b" "e" 

As you can see, the resulting vector is shorter than the original input list, which is a problem if I want to append it as a column in a longer dataframe. My expected result is a vector of the same length of the original list:

[1] "a" NA  "c"

How do I deal with NAs when using lapply to select subelements within a list?

Upvotes: 1

Views: 173

Answers (1)

r2evans
r2evans

Reputation: 160417

Always look for at least the first one ... we can use max here:

unlist(lapply(MyList, function(x) return(x[max(1,length(x)-1)])))
#   a   b   c 
# "b"  NA "e" 

or alternatively

sapply(MyList, function(x) return(x[max(1,length(x)-1)]))
mapply(`[[`, MyList, pmax(1, lengths(MyList)-1))

Upvotes: 2

Related Questions