0

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.

3
  • 3
    ifelse(names(my_vec) == "", my_vec, names(my_vec))?
    – lroha
    Commented Jul 11, 2023 at 3:43
  • 1
    Thanks! I guess easy enough to put this in a function. :)
    – JRR
    Commented Jul 11, 2023 at 3:55
  • you can also make use of the nzchar function ifelse(nzchar(nms<-names(my_vec)), nms, my_vec)
    – Onyambu
    Commented Jul 11, 2023 at 5:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.