Search code examples
rvector

How to swap the names and values of a named vector in R?


I am interested in swapping the names and values of my vector

y <- c(a = "Apple", b = "Banana")

I would instead like code that creates the equivalent of

y <- c(Apple = "a", Banana = "b")

I see there is the invert function in the the searchable package, but this doesn't seem like it's updated for Version 4 of R yet.


Solution

  • You can use :

    setNames(names(y), y)
    # Apple Banana 
    #   "a"    "b"