I have a vector that is partially named. All values (and names) are distinct.
my_vec <- c('one',
'two' = '2',
'three' = '3')
Sometimes I need the values i.e. unique(my_vec)
which returns c("one","2","3")
. I now need the
"opposite" that is: c("one","two", "three")
. Note that names
is insufficient because the vector is partially named.
Is there a base R or tidy way to return the names of vector elements where available and vector values otherwise?
Apologies, this feels like something that should have an easily accessible answer on here but I can't find it anywhere.
ifelse(names(my_vec) == "", my_vec, names(my_vec))
?nzchar
functionifelse(nzchar(nms<-names(my_vec)), nms, my_vec)