18

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.

John-Henry
  • 1,556
  • 8
  • 20
  • You can install the `searchable` package. Please check my solution below – akrun Nov 21 '20 at 00:03
  • note for posterity: this question is related to names at values at the vector level. At the column level, you would use a very similar solution, see: https://stackoverflow.com/a/43337009/10952717 for useful information – John-Henry Dec 08 '20 at 20:56

2 Answers2

30

You can use :

setNames(names(y), y)
# Apple Banana 
#   "a"    "b" 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
3

We can use enframe/deframe

library(tibble)
enframe(y) %>% 
    select(2:1) %>% 
    deframe
#  Apple Banana 
#  "a"    "b" 

It is possible to install the package from the archive. Download the tar file in working directory, use install.packages with local = TRUE

install.packages("searchable_0.3.3.1.tar.gz", local = TRUE)
#inferring 'repos = NULL' from 'pkgs'
#* installing *source* package ‘searchable’ ...
#** package ‘searchable’ successfully unpacked and MD5 sums checked
#** using staged installation
#** R
#** byte-compile and prepare package for lazy loading
#** help
#*** installing help indices
#** building package indices
#** testing if installed package can be loaded from temporary location
#** testing if installed package can be loaded from final location
#** testing if installed package keeps a record of temporary installation path
#* DONE (searchable)

Now, we can test it

library(searchable)
invert(y)
#  Apple Banana 
#   "a"    "b" 
akrun
  • 874,273
  • 37
  • 540
  • 662