I am looking for the most efficient form to transform
ARTNR FILGRP
1 1 9827
2 2 9348
3 3 9335, 9827, 9339
into this
ARTNR FILGRP
1 1 9827
2 2 9348
3 3 9335
4 3 9827
5 3 9339
I tried the following code and it works, but it is not elegant and has some shortcomings. :
setDT(artnrs)
artnrs[, c("P1", "P2", "P3") := tstrsplit(FILGRP, ",", fixed=TRUE)] # 1)
artnrs <- melt(artnrs, c("ARTNR"), measure = patterns("^P")) # 2)
artnrs[,variable:=NULL] # 3)
artnrs <- na.omit(artnrs, cols="value") # 4)
names(artnrs)[2] <- "FILGRP" # 5)
- ad 1) splits the last column in three new ones. How can I make this dynamic and make it fit for five or ten?
- ad 2-5) rather clumpsy operations, could I chain this better?
It is based on data.table
but performance is not that critical so an easy to understand tidyverse
solution would be ok. But the fewer packages, the better.
Thanks!
dput
output;
structure(list(ARTNR = c(1, 2, 3), FILGRP = c("9827", "9348", "9335, 9827, 9339")),
row.names = c(NA, -3L), class = "data.frame")
question from:
https://stackoverflow.com/questions/65943165/more-dynamic-melting-with-data-table 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…