I'm trying to take a list of vectors and if the vector has 3 or more elements I want to grab element 3. If it does not have 3 elements, I want to grab whichever element is the last one. I can't wrap my head around how to do this. I thought I could use if_else along with pluck but I'm not getting far:
library(tidyverse)
lst <- list("this/that/theother/notthis",
"this",
"",
"this/that")
lst %>%
str_split(., "/") %>%
if_else(length(.) >= 3, pluck(3), pluck(length(.)))
#> Error: `condition` must be a logical, not list
In this example I would like the result to return a list with three elements: "theother", "this","","that". I would not be stressed if the vector with no records returned NA, but I do need at least an empty placeholder there.
Very nice! Thank you. I tend to use pluck instead of [[ only because it saves me a few WTFs later. And I like to conserve my WTFs for when I really need them.