0

I have the next dataframe:

col1<-c("A1","B1","A1","B1","C1","C1","A1")
col2<-c("a","b","c","d","b","f","a")
dat<-data.frame(col1,col2)

From the previous data frame I would like to get something like this:

A1   "ac"
B1   "bd" 
C1   "bf"

I mean, I need to aggregate by paste unique values in col 2 grouping the codes in col1.

I was trying something like this

   dat%>%group_by(col1)%>%summarise(pp=paste0(col2))

but It doesn't work.

user3483060
  • 337
  • 2
  • 13

1 Answers1

0

Do this on the unique rows. Also, paste0 by itself doesn't work. it needs the additional argument collapse

 aggregate(col2~ col1, unique(dat), FUN = paste, collapse="")

library(dplyr)
library(stringr)
dat %>%
   distinct %>%
   group_by(col1) %>%
   summarise(pp = str_c(col2, collapse=""), .groups = 'drop')

-output

# A tibble: 3 x 2
  col1  pp   
  <chr> <chr>
1 A1    ac   
2 B1    bd   
3 C1    bf   
akrun
  • 874,273
  • 37
  • 540
  • 662