粘贴向量列表的多个元素

Paste multiple elements of a list of vectors

我有一个这样的数据table

        ID           Name
1: 2760925   01_HOOFD_010
2: 2760925   01_HOOFD_015
3: 2771451   01_HOOFD_010
4: 2771451 01_HOOFD_190_2
5: 2771451 01_HOOFD_030_2
6: 2771451 08_AWB45_020_2
7: 2771451   08_AWB45_040
8: 2771451 01_HOOFD_065_2

对于 "Name" 字段,我希望将第二个下划线之后的部分放在单独的 data.table 列中。 目前,我使用带有“_”作为标记的 strplit,但我的问题是有些记录有 3 个元素,有些记录有 4 个元素。 我目前的解决方案是

DT$code_3<-DT[,.(lapply(strsplit(Name,"_"),"[",3:4)),][,.(lapply(V1,function(x) paste(na.omit(x),collapse="_"))),]

但我怀疑这是否是最真实/简洁的方式... 你有什么更好的主意吗? 谢谢

> dput(DT)
structure(list(ID = c(2760925L, 2760925L, 2771451L, 2771451L, 
2771451L, 2771451L, 2771451L, 2771451L), Name = c("01_HOOFD_010", 
"01_HOOFD_015", "01_HOOFD_010", "01_HOOFD_190_2", "01_HOOFD_030_2", 
"08_AWB45_020_2", "08_AWB45_040", "01_HOOFD_065_2")), .Names = c("ID", 
"Name"), row.names = c(NA, -8L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x103819178>)
x <-structure(list(ID = c(2760925L, 2760925L, 2771451L, 2771451L, 
2771451L, 2771451L, 2771451L, 2771451L), Name = c("01_HOOFD_010", 
"01_HOOFD_015", "01_HOOFD_010", "01_HOOFD_190_2", "01_HOOFD_030_2", 
"08_AWB45_020_2", "08_AWB45_040", "01_HOOFD_065_2")), .Names = c("ID", 
"Name"), row.names = c(NA, -8L), class = c("data.table", "data.frame"
))

x$two <- gsub( "(.*?)_(.*?)_(.*?)" , "" , x$Name )