DJC
DJC

Reputation: 1611

Selecting elements of a named vector using dplyr/tidyr

Very simple question that I can't figure out for some reason.

I have a named vector:

dat <- c("Clyde" = 1, "Susy" = 2, "Frank" = 3, "John" = 4)

How do I select just Clyde and Frank's numbers using dplyr? The code below doesn't seem to be doing it.

dat %>% select(Clyde, Frank)

Am sure its a super easy solution, just can't figure it out. Thanks!

Upvotes: 2

Views: 1066

Answers (1)

akrun
akrun

Reputation: 887961

The select works when the data is data.frame and not on named vector. One option would be to convert to a two column tibble with enframe (from tibble), filter the 'name' columns and then deframe to create the named vector

library(tibble)
librarry(dplyr)
dat %>%
    enframe %>% 
    filter(name %in% c("Clyde", "Frank")) %>%
    deframe
#  Clyde Frank 
#   1     3 

If we are using magrittr another option is extract (not that there is a similar function in tidyr - behaviour different) which is alias for [

library(magrittr)
dat %>%
    extract(c("Clyde", "Frank"))
#   Clyde Frank 
#    1     3 

Or if we want to use select, convert it to a 4 -column data.frame/tibble

dat %>% 
    t %>% 
    as_tibble %>%
    select(Clyde, Frank)

Here, we convert it to a matrix first with transposing the vector (as vector and matrix can hold only a single class, it is okay), then convert it to a tibble (as_tibble) and use select to select the columns with unquoted column names


In base R, it is simply using the names

dat[c("Clyde", "Frank")]

Upvotes: 3

Related Questions