简体   繁体   中英

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 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.

You can use :

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

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM