0

I need to get a vector of unique values from filtered dataframe data using dplyr library.

Dummy example:

df<-data.frame(site =  letters[seq( from = 1, to = 5)],
               year = c(1,2,2,3,4))

  site year
1    a    1
2    b    2
3    c    2
4    d    3
5    e    4  

I want to print out a vector of sites where year == 2.

The dplyr package returns a dataframe. How to turn it to a vector?

df %>% 
  filter(year == 2) %>% 
  select(site) #
#  unique ???   how to convert the filtered dataframe to vector?

I know how to make this in two steps using classical approach: filter the dataframe and than access the column:

# Filter data and get a new dataframe:

df2<-df %>% 
  dplyr::filter(year == 2) %>% 
  select(site)

# Check the column values after filtering:
df2$site

But I am sure there is a nicer way in dplyr?

Expected output:

[1] b c
2
  • 5
    Use pull, df %>% filter(year == 2) %>% pull(site)
    – Ronak Shah
    Jul 17, 2019 at 6:50
  • 1
    Awesome! I could not find this example! Thank you @RonakShah
    – maycca
    Jul 17, 2019 at 7:28

0

Browse other questions tagged or ask your own question.