Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapse column value into one if different value [duplicate]

Tags:

r

dplyr

I have a df that looks like the follow:

ID   LOC
1     A
1     A
2     A
2     B
3     A
3     A
3     A
4     A
4     B
4     C

What I would like to do is collapse the LOC values to one row per ID and if they are the same keep it as one value, so my output would be:

ID   LOC
1     A
2     A + B
3     A
4     A + B + C

Right now I am using:

group_by(ID) %>%
mutate(concat_LOC = paste0(LOC, collapse = " + ")) 

which concats all values even if they are the same

like image 969
user3249770 Avatar asked May 21 '26 14:05

user3249770


1 Answers

  1. You're reducing/summarizing, so you should use summarize instead of mutate.
  2. Since you do want to repeat LOC values, use unique.
dat %>%
  group_by(ID) %>%
  summarize(LOC = paste(unique(LOC), collapse = " + ")) %>%
  ungroup()
# # A tibble: 4 x 2
#      ID LOC      
#   <int> <chr>    
# 1     1 A        
# 2     2 A + B    
# 3     3 A        
# 4     4 A + B + C
like image 96
r2evans Avatar answered May 24 '26 03:05

r2evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!