logjammin
logjammin

Reputation: 1211

filtering in R's dplyr with 2 conditions

I have a dataframe in R, it looks like this:

df <- data.frame(ID = c("a","b","c","d","e","f"), 
                is_private = c("y","y","n","n","n","y"), 
                insurer =c("uhc","aetna","medicare","medicare","medicaid","oscar"), stringsAsFactors=FALSE) 

I'm trying to use dplyr::filter to get a list of unique names of df$insurer for only those whose value of df$is_private is 'n'.

What I want is a list or df that looks like this:

uniques
-------
medicare
medicaid

I keep trying things like:

pub_list <- df$insurer %>%
  filter(df$is_private == "n") %>%
  unique()

But all I get are error messages that say no applicable method for 'filter' applied to an object of class "character"

Upvotes: 0

Views: 44

Answers (2)

LMc
LMc

Reputation: 18732

In base R:

unique(df[df$is_private == "n", "insurer", drop = F])

Upvotes: 0

tonybot
tonybot

Reputation: 655

distinct() might be better.

df %>%
  filter(is_private == "n") %>%
  distinct(insurer)

Upvotes: 2

Related Questions