Cro*_*ops 1 r data.table stringi
我有一个data.table DT如下.
DT <- structure(list(V1 = structure(1:3, .Label = c("S01", "S02", "S03" ), class = "factor"), V2 = structure(c(1L, 3L, 2L), .Label = c("Alan Hal << Guy John", "Bruce Dick Jean-Paul << Damien", "Jay << Barry Wally Bart"), class = "factor")), .Names = c("V1", "V2"), row.names = c(NA, -3L), class = "data.frame")
# DT
# V1 V2
# 1 S01 Alan Hal << Guy John
# 2 S02 Jay << Barry Wally Bart
# 3 S03 Bruce Dick Jean-Paul << Damien
setDT(DT)
Run Code Online (Sandbox Code Playgroud)
我试图V2在"<<" 分割列,并在两个新列中获取输出.
我可以按照以下方式完成它 stringi
T <- as.data.frame(do.call(rbind, stri_split_fixed(DT$V2, "<<", 2)))
setnames(T, old = colnames(T), new = c("V3", "V4"))
cbind(DT, T)
V1 V2 V3 V4
1: S01 Alan Hal << Guy John Alan Hal Guy John
2: S02 Jay << Barry Wally Bart Jay Barry Wally Bart
3: S03 Bruce Dick Jean-Paul << Damien Bruce Dick Jean-Paul Damien
Run Code Online (Sandbox Code Playgroud)
但是我想通过:=运算符引用来做同样的事情.如何使用data.table执行此操作?
我对RHS部分有困难.
DT[, c("V1", "V2) := list()]
Run Code Online (Sandbox Code Playgroud)
stri_split_fixed(DT$V2, "<<", 2) 给出一个3的列表,其中包含长度为2的字符向量.如何获得长度为3的字符向量的2列表?
你可以试试
setDT(DT)[, c('V3', 'V4'):=do.call(rbind.data.frame,
stri_split_fixed(V2, ' << ', 2))][]
# V1 V2 V3 V4
#1: S01 Alan Hal << Guy John Alan Hal Guy John
#2: S02 Jay << Barry Wally Bart Jay Barry Wally Bart
#3: S03 Bruce Dick Jean-Paul << Damien Bruce Dick Jean-Paul Damien
Run Code Online (Sandbox Code Playgroud)
或者你可以使用strsplit(来自@David Arenburg的评论)
setDT(DT)[, c('V3', 'V4'):= do.call(rbind.data.frame,
strsplit(as.character(V2), " << "))]
Run Code Online (Sandbox Code Playgroud)
更有效的选择(由@Ananda Mahto建议)
cbind(DT, `colnames<-`(stri_split_fixed(DT$V2,
" << ", simplify = TRUE), c("V3", "V4")))
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用cSplit由splitstackshape
library(splitstackshape)
cSplit(DT, 'V2', ' << ', stripWhite=FALSE, drop=FALSE)
# V1 V2 V2_1 V2_2
#1: S01 Alan Hal << Guy John Alan Hal Guy John
#2: S02 Jay << Barry Wally Bart Jay Barry Wally Bart
#3: S03 Bruce Dick Jean-Paul << Damien Bruce Dick Jean-Paul Damien
Run Code Online (Sandbox Code Playgroud)
的更快的版本cSplit赋予类似性能stri_split是可Gist