Using dplyr
, one way would be
library(dplyr)
df %>%
group_by(ID) %>%
mutate(new_name = paste0(Country,collapse = " + "),
new_name = replace(new_name, duplicated(new_name), NA))
# ID Country new_name
# <int> <fct> <chr>
# 1 55 Poland Poland + Romania + France
# 2 55 Romania NA
# 3 55 France NA
# 4 98 Spain Spain + Portugal + UK
# 5 98 Portugal NA
# 6 98 UK NA
# 7 65 Germany Germany
# 8 67 Luxembourg Luxembourg
# 9 84 Greece Greece
#10 22 Estonia Estonia + Lithuania
#11 22 Lithuania NA
However, to get your exact expected output we might need
df %>%
group_by(ID) %>%
mutate(new_name = if (n() > 1)
paste0("Countries ", paste0(Country,collapse = " + ")) else Country,
new_name = replace(new_name, duplicated(new_name), NA))
# ID Country new_name
# <int> <fct> <chr>
# 1 55 Poland Countries Poland + Romania + France
# 2 55 Romania NA
# 3 55 France NA
# 4 98 Spain Countries Spain + Portugal + UK
# 5 98 Portugal NA
# 6 98 UK NA
# 7 65 Germany Germany
# 8 67 Luxembourg Luxembourg
# 9 84 Greece Greece
#10 22 Estonia Countries Estonia + Lithuania
#11 22 Lithuania NA