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.
Thoughts on how I might elegantly do this?