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
maycca
  • 2,960
  • 2
  • 22
  • 47

0 Answers0