Question: I want to generate a new column to show the Period data using IDs.

My data are similar to this data

```html
df1<-read.table(text="ID Location Day Period Group
241 A am M1 A
231 D am N1 A
241 N pm M2 A
234 K pm N2 B
231 G pm N2 B
300 K am M2 A",header=TRUE)
```

and the the expected data are:

```html
df1<-read.table(text="ID Location Day Period Group Match
241 A am M1 A M2
231 D am N1 A N2
234 K pm N2 B NA
300 K am M2 A NA",header=TRUE)
```

If there are duplicated IDs, only one Id is kept and the value of the period is addressed in the Match column. I want to have blank instead of NA

Answer: 
Try this

```
library(dplyr)

df1 %>% 
  filter(!duplicated(ID)) %>% 
  left_join(
    df1 %>% 
      filter(duplicated(ID)) %>% 
      select(ID, Period), by = "ID") %>% 
  rename(Period = Period.x, Match = Period.y)

```

or using `group_split`

```
library(dplyr)
library(purrr)

df1 %>% 
  mutate(is_duplicated = duplicated(ID)) %>% 
  group_split(is_duplicated, keep = FALSE) %>% 
  reduce(left_join, by = "ID", suffix = c("", "_match")) %>% 
  select(names(df1), Match = Period_match) 

```
After grouping by 'ID', we can get the `first` element of 'Group', 'Day', 'Location', and return the second element of 'Match'

```
library(dplyr)
df1 %>%
   group_by(ID) %>% 
   summarise(Group = first(Group), Day = first(Day),
             Location = first(Location),
             Match = Period[2], Period = first(Period))
# A tibble: 4 x 6
#     ID Group Day   Location Match Period
#  <int> <fct> <fct> <fct>    <fct> <fct> 
#1   231 A     am    D        N2    N1    
#2   234 B     pm    K        <NA>  N2    
#3   241 A     am    A        M2    M1    
#4   300 A     am    K        <NA>  M2    

```

---

Or another option is to `mutate` the columns with the `first` value after grouping by 'ID' and then do the `summarise`

```
df1 %>%
    group_by(ID) %>% 
    mutate_at(vars(Group, Day, Location), first) %>%
    group_by(Group,  Day, Location , .add= TRUE) %>%
    summarise(Match = Period[2],   Period = first(Period))
# A tibble: 4 x 6
# Groups:   ID, Group, Day [4]
#     ID Group Day   Location Match Period
#  <int> <fct> <fct> <fct>    <fct> <fct> 
#1   231 A     am    D        N2    N1    
#2   234 B     pm    K        <NA>  N2    
#3   241 A     am    A        M2    M1    
#4   300 A     am    K        <NA>  M2    

```

---

In the `devel` version of `dplyr`, this can be made more compact with `across`

```
df1 %>% 
   group_by(ID) %>% 
   summarise(across(c(Group, Day, Location), first),
              Match = Period[2], Period = first(Period))
# A tibble: 4 x 6
#     ID Group Day   Location Match Period
#  <int> <fct> <fct> <fct>    <fct> <fct> 
#1   231 A     am    D        N2    N1    
#2   234 B     pm    K        <NA>  N2    
#3   241 A     am    A        M2    M1    
#4   300 A     am    K        <NA>  M2    

```

Here, we assume that there would be no more than 2 rows per unique 'ID'