Cina
Cina

Reputation: 10199

need help in using paste0 in group_by in R

I have df as below and I would like to add new column to adds up col1 based on ID. I write code with pdlyr, but I don't know how to fix it.

df %>%
  group_by(ID) %>%
  mutate(col2= paste0(col1,?????)   <- what to write here?

df<-read.table(text="
ID   col1
1      A
1      B
1      A
2      C     
2      C
2      D", header=T)
result
ID   col1   col2
1      A     ABA
1      B     ABA
1      A     ABA
2      C     CCD
2      C     CCD
2      D     CCD

Upvotes: 1

Views: 500

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269694

Use the collapse argument.

df %>%
  group_by(ID) %>%
  mutate(col2= paste(col1, collapse = "")) %>%
  ungroup

giving:

# A tibble: 6 x 3
     ID col1  col2 
  <int> <fct> <chr>
1     1 A     ABA  
2     1 B     ABA  
3     1 A     ABA  
4     2 C     CCD  
5     2 C     CCD  
6     2 D     CCD  

Alternately using only base R we could use this one-liner:

transform(df, col2 = ave(as.character(col1), ID, FUN = function(x) paste(x, collapse = "")))

giving:

  ID col1 col2
1  1    A  ABA
2  1    B  ABA
3  1    A  ABA
4  2    C  CCD
5  2    C  CCD
6  2    D  CCD

Upvotes: 3

Related Questions