Q:

Create new column to long data format if group have more than one factor level?

I would like to subset and recreate a new column to my long format data based on the number of levels on each factors. 
For example, site a can have either distance b20 or b5, but site b and c have only single value for distance (b20). 
If there are more factors, my new column source should hold value "unclear", if there is only one factor, use the distance value in according row. 
# Dummy data frame
df<- data.frame(year = c(1,1,2,1,5,5,10),
                distance = c("b20", "b5", "b20", "b20", "PA", "b5", "PA"),
                site     = c("a", "a", "b", "c", "d", "d", "e"))

    > df
  year distance site
1    1      b20    a  # `a` has more than 1 distances => source == unclear
2    1       b5    a
3    2      b20    b
4    1      b20    c
5    5       PA    d  # `d` has more than 1 distances => source == unclear
6    5       b5    d
7   10       PA    e

Desired output:
 > df
  year distance site source
1    1      b20    a unclear 
2    1       b5    a unclear
3    2      b20    b b20
4    1      b20    c b20
5    5       PA    d unclear
6    5       b5    d unclear
7   10       PA    e PA

A:

We can use a simple ifelse statement,
library(dplyr)

df %>% 
 group_by(site) %>% 
 mutate(source = ifelse(n_distinct(distance) == 1, as.character(distance[1]), 'unclear'))

which gives,

# A tibble: 7 x 4
# Groups:   site [5]
   year distance site  source 
  <dbl> <fct>    <fct> <chr>  
1     1 b20      a     unclear
2     1 b5       a     unclear
3     2 b20      b     b20    
4     1 b20      c     b20    
5     5 PA       d     unclear
6     5 b5       d     unclear
7    10 PA       e     PA

