拆分字符列并获取字符串中的字段名称

Cat*_*ath 6 r reshape data.table

我需要将包含信息的列拆分为几列。
我会使用,tstrsplit但是:相同的信息在行之间的顺序不相同,并且我需要提取变量中新列的名称。重要信息:可能有很多信息(字段变成新变量),我不知道所有这些信息,因此我不希望采用“逐字段”解决方案。

以下是我所拥有的示例:

library(data.table)

myDT <- structure(list(chr = c("chr1", "chr2", "chr4"), pos = c(123L,
                  435L, 120L), info = c("type=3;end=4", "end=6", "end=5;pos=TRUE;type=2"
                  )), class = c("data.table", "data.frame"), row.names = c(NA,-3L))

#    chr pos                  info
#1: chr1 123          type=3;end=4
#2: chr2 435                 end=6
#3: chr4 120 end=5;pos=TRUE;type=2
Run Code Online (Sandbox Code Playgroud)

我想得到:

#    chr pos end  pos type
#1: chr1 123   4 <NA>    3
#2: chr2 435   6 <NA> <NA>
#3: chr4 120   5 TRUE    2
Run Code Online (Sandbox Code Playgroud)

最简单的方法将不胜感激!(注意:我不愿意采用dplyr / tidyr的方式

sin*_*dur 5

使用regexstringi软件包:

setDT(myDT) # After creating data.table from structure()

library(stringi)

fields <- unique(unlist(stri_extract_all(regex = "[a-z]+(?==)", myDT$info)))
patterns <- sprintf("(?<=%s=)[^;]+", fields)
myDT[, (fields) := lapply(patterns, function(x) stri_extract(regex = x, info))]
myDT[, !"info"]

    chr  pos type end
1: chr1 <NA>    3   4
2: chr2 <NA> <NA>   6
3: chr4 TRUE    2   5
Run Code Online (Sandbox Code Playgroud)

编辑:要获得正确的类型,似乎type.convert()可以使用(?):

myDT[, (fields) := lapply(patterns, function(x) type.convert(stri_extract(regex = x, info), as.is = TRUE))]
Run Code Online (Sandbox Code Playgroud)