sclee1
sclee1

Reputation: 1281

Concatenate row-based into one column delimited by character in r

I am trying to convert the data into the format what I want. The data looks as follows

id   num   time
0     3    4:34
0     4    4:35
0     5    4:36
1     100  5:1
1     200  5:2

And then I want to convert it to below format.

id    converted format
0   3,4,5;4:34,4:35,4:36
1   100,200;5:1,5:2

As you can see, the data is combined by the id and I concatenated them using num and time and used the comma delimiter for each item values and used the ; for distinguish num and time.

How can I achieve my goals using R? I appreciate any answers that help my issue.

Thanks.

Upvotes: 1

Views: 43

Answers (2)

akrun
akrun

Reputation: 886948

Here is an option with tidyverse

library(dplyr)
df1 %>% 
   group_by(id) %>% 
   summarise_all(toString) %>% 
   unite(convertedformat, num, time, sep="; ")

Upvotes: 1

nghauran
nghauran

Reputation: 6768

data.table should help here.

data <- data.frame(id = c(0, 0, 0, 1, 1),
                   num = c(3, 4, 5, 100, 200),
                   time = c("4:34", "4:35", "4:36", "5:1", "5:2"))
library(data.table)
setDT(data)
data[ , .(converted_format = paste(paste(num, collapse = ","), paste(time, collapse = ","),
          sep = ";")),
      by = id]

Upvotes: 1

Related Questions