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?