Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting and creating 2 rows out of one in R data table

Tags:

r

datatable

I have a dataset (dt) like this in R:

n       id      val
1       1&&2    10
2       3       20
3       4&&5    30

And what I want to get is

n       id      val
1       1       10
2       2       10
3       3       20
4       4       30
5       5       30

I know that to split ids I need to do something like this: id_split <- strsplit(dt$id,"&&")

But how do I create new rows with the same val for ids which were initially together in a row?

like image 427
Anya Pilipentseva Avatar asked Oct 19 '25 07:10

Anya Pilipentseva


1 Answers

You may cbind the splits to get a column which you cbind again to the val (recycling).

res <- do.call(rbind, Map(data.frame, id=lapply(strsplit(dat$id, "&&"), cbind), 
                          val=dat$val))
res <- cbind(n=1:nrow(res), res)
res
#   n id val
# 1 1  1  10
# 2 2  2  10
# 3 3  3  20
# 4 4  4  30
# 5 5  5  30
like image 62
jay.sf Avatar answered Oct 21 '25 20:10

jay.sf



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!