Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

r - more dynamic melting with data.table

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
df <- structure(list(ARTNR = c(1, 2, 3), FILGRP = c("9827", "9348", "9335, 9827, 9339")), 
          row.names = c(NA, -3L), class = "data.frame")

df2 <- strsplit(df$FILGRP, split = ",")
df2 <- data.frame(ARTNR = rep(df$ARTNR, sapply(df2, length)), FILGRP = unlist(df2))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...