Question: I have a data frame like this:

```
dat1 <- data.frame(Unit = c("a","a","b","c","c","c","d"), Habitat = c("choppy sands","sands","meadow","sands","meadow","choppy sands","choppy sands"), Litter = c(3.7,3.4,5.6,2.1,3.6,7.5,1.2))

>dat1
  Unit      Habitat Litter
1    a choppy sands    3.7
2    a        sands    3.4
3    b       meadow    5.6
4    c        sands    2.1
5    c       meadow    3.6
6    c choppy sands    7.5
7    d choppy sands    1.2

```

I want to find and remove duplicate rows based on Unit where the single row to keep for each value of Unit depends on a hierarchy of values in Habitat. If there are duplicate rows based on Unit, a row where Habitat = "meadow" takes first priority, then a row where Habitat = "choppy sands", then a row where Habitat = "sands". So the resulting data frame would look like this:

```
  Unit      Habitat Litter
1    a choppy sands    3.7
2    b       meadow    5.6
3    c       meadow    3.6
4    d choppy sands    1.2

```

Any help much appreciated.

Answer: 
Using `dplyr` and `forcats` (both in the `tidyverse` system of packages), you could do something like this:

```
dat2 <- 
    dat1 %>%
    mutate(Habitat = fct_relevel(Habitat, c('meadow', 'choppy sands', 'sands'), after=0L)) %>%
    group_by(Unit) %>%
    filter(as.numeric(Habitat) == min(as.numeric(Habitat)))

```

This gives the desired output. The idea is that you make `Habitat` a factor variable and encode your hierarchy in the levels of this variable. Then, (within each `Unit` group), you keep the rows that have the highest priority `Habitat` by filtering using the `as.numeric(Habitat) == min(as.numeric(Habitat))` rule.
Here is a base R solution. I used the `factor` function to set the preferred order for the habitat. Then ordering the dataframe by Unit and Habitat. Finally removed the duplicates leaving the first row of the unique Units.

```
dat1 <- data.frame(Unit = c("a","a","b","c","c","c","d"), Habitat = c("choppy sands","sands","meadow","sands","meadow","choppy sands","choppy sands"), Litter = c(3.7,3.4,5.6,2.1,3.6,7.5,1.2))

#Use the factor function to order the Habitat in the preferred order
dat1$Habitat<-factor(dat1$Habitat, levels= c("meadow", "choppy sands","sands"))

#order by Unit then by preferred Habitat
dat1<-dat1[order(dat1$Unit, dat1$Habitat),]

#Should retain the first unique row for each Unit
dat1[!duplicated(dat1$Unit),]

```