Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tstrsplit to different columns in one round

Tags:

r

data.table

I have a table like the following:

myDT <- fread(
  "id,other,strformat,content
 1, other1, A:B,    a1:b1
 2, other2, A:C,    a2:c2
 3, other3, B:A:C,  b3:a3:c3
 4, other4, A:B,    a4:b4
 5, other5, XX:whatever,    xx5:whatever5
")

And I want to split the content column based on strformat, to get this:

   id  other   strformat       content    A    B    C   XX  whatever
1:  1 other1         A:B         a1:b1   a1   b1 <NA> <NA>      <NA>
2:  2 other2         A:C         a2:c2   a2 <NA>   c2 <NA>      <NA>
3:  3 other3       B:A:C      b3:a3:c3   a3   b3   c3 <NA>      <NA>
4:  4 other4         A:B         a4:b4   a4   b4 <NA> <NA>      <NA>
5:  5 other5 XX:whatever xx5:whatever5 <NA> <NA> <NA>  xx5 whatever5

I failed with tstrsplit() on by=:

myDT[, unlist(strsplit(strformat,':')):=tstrsplit(content,':'), by=strformat]
# Error in strsplit(strformat, ":") : object 'strformat' not found

So for now I resorted to using a cycle:

for (this.format in unique(myDT$strformat)){
  myDT[strformat==this.format, unlist(strsplit(this.format,':')):=tstrsplit(content,':')]
}

It does the job, but I'm still wondering what would be the right way with by=

like image 937
Vasily A Avatar asked Oct 16 '22 15:10

Vasily A


1 Answers

So, I have tested 3 solutions kindly suggested by @akrun, with slight modifications. Skipped the last one because it has the column names hardcoded.

# define functions to compare:

require(splitstackshape)
f_csplit <- function(inpDT, col_format='strformat', col_content='content', sep=':'){
  invisible(inpDT[dcast(
    cSplit(inpDT, c(col_format, col_content), sep, "long"), 
    as.formula(paste('id',col_format,sep='~')), 
    value.var=col_content
  ), , on = .(id)])
}

f_lapply_str <- function(inpDT, col_format='strformat', col_content='content', sep=':'){
  invisible(inpDT[dcast(
    inpDT[, unlist(lapply(.SD, strsplit, sep), recursive = FALSE), by = id, .SDcols = 2:3], 
    as.formula(paste('id',col_format,sep='~')),
    value.var=col_content
  ), on = .(id)])
}

require(tidyverse)
f_unnest <- function(inpDT, col_format='strformat', col_content='content', sep=':'){
  invisible(inpDT[dcast(
    unnest(inpDT[, lapply(.SD, tstrsplit, sep),by = id, .SDcols = 2:3]), 
    as.formula(paste('id',col_format,sep='~')), 
    value.var=col_content
  ), on = .(id)])
}

f_cycle <- function(inpDT, col_format='strformat', col_content='content', sep=':'){
  inpDT <- copy(inpDT); # in fact I don't even need to make a copy:
                        # := modifies the original table which is fine for me - 
                        # but for benchmarking let's make a copy  
  for (this.format in unique(inpDT[[col_format]])){
    inpDT[get(col_format)==this.format, unlist(strsplit(this.format,sep)):=tstrsplit(get(col_content),sep)]
  }
  invisible(inpDT)
}

It seems that solutions #2 (lapply of strsplit, without cSplit) and #3 (unnest) don't work correctly when I have any other columns in the table, it only works if I remove "other":

myDT[dcast(myDT[, unlist(lapply(.SD, strsplit, ":"), recursive = FALSE), by = id, .SDcols = 2:3], id ~ strformat), on = .(id)]
#      id  other   strformat       content    A    B    C   XX whatever
#   1:  1 other1         A:B         a1:b1    A    B <NA> <NA>     <NA>
#   2:  2 other2         A:C         a2:c2    A <NA>    C <NA>     <NA>
#   3:  3 other3       B:A:C      b3:a3:c3    A    B    C <NA>     <NA>
#   4:  4 other4         A:B         a4:b4    A    B <NA> <NA>     <NA>
#   5:  5 other5 XX:whatever xx5:whatever5 <NA> <NA> <NA>   XX whatever

myDT[dcast(unnest(myDT[, lapply(.SD, tstrsplit, ":"),by = id, .SDcols = 2:3]), id ~ strformat), on = .(id)]
# (same result as above)

myDT$other <- NULL
myDT[dcast(myDT[, unlist(lapply(.SD, strsplit, ":"), recursive = FALSE), by = id, .SDcols = 2:3], id ~ strformat), on = .(id)]
#      id   strformat       content    A    B    C   XX  whatever
#   1:  1         A:B         a1:b1   a1   b1 <NA> <NA>      <NA>
#   2:  2         A:C         a2:c2   a2 <NA>   c2 <NA>      <NA>
#   3:  3       B:A:C      b3:a3:c3   a3   b3   c3 <NA>      <NA>
#   4:  4         A:B         a4:b4   a4   b4 <NA> <NA>      <NA>
#   5:  5 XX:whatever xx5:whatever5 <NA> <NA> <NA>  xx5 whatever5

myDT[dcast(unnest(myDT[, lapply(.SD, tstrsplit, ":"),by = id, .SDcols = 2:3]), id ~ strformat), on = .(id)]
# (same correct result as above)

Here is the benchmarking with "other" columns removed:

# make a bigger table based on a small one:
myDTbig <- myDT[sample(nrow(myDT),1e5, replace = T),]
myDTbig[, id:=seq_len(nrow(myDTbig))]
myDTbig$other <- NULL

require(microbenchmark)
print(microbenchmark(
  f_csplit(myDTbig), 
  f_lapply_str(myDTbig), 
  f_unnest(myDTbig), 
  f_cycle(myDTbig), 
  times=10L
), signif=2)

# Unit: milliseconds
#              expr      min   lq mean median   uq  max neval
# f_csplit(myDTbig)      420  430  470    440  450  670    10
# f_lapply_str(myDTbig) 4200 4300 4700   4700 5100 5400    10
# f_unnest(myDTbig)     3900 4400 4500   4500 4800 5100    10
# f_cycle(myDTbig)        88   96   98     98  100  100    10

And with "other" columns kept:

# make a bigger table based on a small one:
myDTbig <- myDT[sample(nrow(myDT),1e5, replace = T),]
myDTbig[, id:=seq_len(nrow(myDTbig))]

require(microbenchmark)
print(microbenchmark(
  f_csplit(myDTbig), 
  f_cycle(myDTbig), 
  times=100L
), signif=2)

# Unit: milliseconds
#              expr min  lq mean median  uq  max neval
# f_csplit(myDTbig) 410 440  500    460 490 1300   100
# f_cycle(myDTbig)   84  93  110     96 100  270   100

And below is with my real dataset. Well, actually, only 1/10th of it: with the full one I had memory allocation error on csplit solution (while the one with the cycle worked fine).

myDTbig <- dt.vcf[1:2e6,]
myDTbig[,id:=seq_len(nrow(myDTbig))]

print(microbenchmark(
  f_csplit(myDTbig, 'FORMAT', 'S_1'), 
  f_cycle(myDTbig, 'FORMAT', 'S_1'), 
  times=5L
), signif=2)
# Unit: seconds
#                              expr  min   lq mean median   uq  max neval
# f_csplit(myDTbig, "FORMAT", "S_1") 15.0 16.0   16   16.0 16.0 17.0     5
# f_cycle(myDTbig, "FORMAT", "S_1")   4.9  4.9    6    5.7  5.8  8.5     5

Finally, I tested if having many levels in format column (i.e. how many cycles we have to run) will increase the time for the solution with the cycle:

myDTbig <- myDT[sample(nrow(myDT),1e6, replace = T),]
myDTbig[, strformat:=paste0(strformat,sample(letters,1e6, replace = T)),]
length(unique(myDTbig$strformat)) # 104
myDTbig[, id:=seq_len(nrow(myDTbig))]

print(microbenchmark(
  f_csplit(myDTbig), 
  f_cycle(myDTbig), 
  times=10L
), signif=2)
# Unit: seconds
#             expr  min  lq mean median  uq max neval
# f_csplit(myDTbig) 7.3 7.4  7.7    7.6 7.9 8.4    10
#  f_cycle(myDTbig) 2.7 2.9  3.0    2.9 3.0 3.8    10

So, as a conclusion - surprisingly, the cycle performed better than anything else for this task.

like image 170
Vasily A Avatar answered Oct 19 '22 00:10

Vasily A