4

I'd like to have dplyr return a character vector instead of a data frame. Is there an easy way to do this?

#example data frame 
df <- data.frame( x=c('a','b','c','d','e','f','g','h'), 
                  y=c('a','a','b','b','c','c','d','d'),
                  z=c('a','a','a','a','a','a','d','d'),
                  stringsAsFactors = FALSE)


#desired output
unique(df$z)
[1] "a" "d"

#dplys's output
df %>% 
  select(z) %>%
  unique() 

z
1 a
7 d
zach
  • 29,475
  • 16
  • 67
  • 88

1 Answers1

7

Try

library(dplyr)
df %>%
   select(z) %>%
   unique() %>% 
   .$z
#[1] "a" "d"

Or using magrittr

library(magrittr)
df %>%
  select(z) %>%
  unique() %>%
  use_series(z)
#[1] "a" "d"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • thanks @akrun the `use_series` is just what the doctor ordered – zach Apr 23 '15 at 19:50
  • @akrun, let's assume that `z` is string column name e.g. `z <- "x"` - how can I subset value then? – Taz May 19 '18 at 13:24
  • @Taz You can use `select_at` `df %>% select_at(z)` or evaluate `df %>% select(!! z)` – akrun May 19 '18 at 14:41
  • @akrun I will get 1x1 data frame - not value of that 1x1 dataframe. But I have already figured it out: `df %>% select(z) %>% unique() %>% use_series(z) %>% .[[1]]` – Taz May 19 '18 at 14:44
  • @Taz I thought you wanted to know how to select it\ – akrun May 19 '18 at 14:44