Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

vector

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

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

I would instead like code the 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.

like image 568
John-Henry Avatar asked Nov 20 '20 15:11

John-Henry


Video Answer


2 Answers

You can use :

setNames(names(y), y)
# Apple Banana 
#   "a"    "b" 
like image 197
Ronak Shah Avatar answered Nov 14 '22 23:11

Ronak Shah


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" 
like image 36
akrun Avatar answered Nov 14 '22 23:11

akrun