0

I have a table with many columns in which I would like to merge all the text in columns into the first one. Like this

ID A B C etc
1 aa bb cc
2 ai ao au

into

ID A B C etc
1 aa,bb,cc
2 ai,ao,au

The problem is the amount of columns, since I can't write their name one by one.

Can you help me?

Thanks a lot!

3 Answers3

0

Does this work:

library(dplyr)

bind_cols(df[1],df %>% rowwise() %>% transmute(A = toString(c_across(cols = -ID))))
  ID          A
1  1 aa, bb, cc
2  2 ai, ao, au

Data used:

df
  ID  A  B  C
1  1 aa bb cc
2  2 ai ao au
Karthik S
  • 11,348
  • 2
  • 11
  • 25
0

There will be a better way to do this, but here's a quick way that works and is easily adapted to your specific needs.

df  <-  data.frame(ID = c(1,2),
                   A = c("aa","ai"),
                   B = c("bb","ao"),
                   C = c("cc", "au"))

for(i in 1:nrow(df)){
  df$A[i]  <- paste0(df[i,2:ncol(df)], collapse = ",")  
}
Phil Lewis
  • 33
  • 4
0
df %>%
  tidyr::unite(col = "unitedcol", A:C, sep = ",")
meriops
  • 997
  • 7
  • 6