我有一个 67MM 行的 data.table,其中人名和姓氏用空格分隔。我只需要为每个单词创建一个新列。
这是数据的一小部分:
n <- structure(list(Subscription_Id = c("13.855.231.846.091.000",
"11.156.048.529.090.800", "24.940.584.090.830", "242.753.039.111.124",
"27.843.782.090.830", "13.773.513.145.090.800", "25.691.374.090.830",
"12.236.174.155.090.900", "252.027.904.121.210", "11.136.991.054.110.100"
), Account_Desc = c("AGUAYO CARLA", "LEIVA LILIANA", "FULLANA MARIA LAURA",
"PETREL SERGIO", "IPTICKET SRL", "LEDESMA ORLANDO", "CATTANEO LUIS RAUL",
"CABRAL CARMEN ESTELA", "ITURGOYEN HECTOR", "CASA CASILDO"),
V1 = c("AGUAYO", "LEIVA", "FULLANA", "PETREL", "IPTICKET",
"LEDESMA", "CATTANEO", "CABRAL", "ITURGOYEN", "CASA"), V2 = c("CARLA",
"LILIANA", "MARIA", "SERGIO", "SRL", "ORLANDO", "LUIS", "CARMEN",
"HECTOR", "CASILDO"), V3 = c(NA, NA, "LAURA", NA, NA, NA,
"RAUL", "ESTELA", NA, NA), `NA` = c(NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_
)), .Names = c("Subscription_Id", "Account_Desc", "V1", "V2",
"V3", NA), class = c("data.table", "data.frame"), row.names = c(NA,
-10L), .internal.selfref = <pointer: 0x0000000000200788>)
require("data.table")
n <- data.table(n)
预期产出
# Subscription_Id Account_Desc V1 V2 V3 NA
# 1: 13.855.231.846.091.000 AGUAYO CARLA AGUAYO CARLA NA NA
# 2: 11.156.048.529.090.800 LEIVA LILIANA LEIVA LILIANA NA NA
# 3: 24.940.584.090.830 FULLANA MARIA LAURA FULLANA MARIA LAURA NA
第一次尝试
如何进行这项工作将是第一个问题
library(stringr)
# This separates the strings, but i loose the Subscription_Id variable.
n[, str_split_fixed(Account_Desc, "[ +]", 4)]
# This doesn't work.
n[, paste0("V",1:4) := str_split_fixed(Account_Desc, "[ +]", 4)]
第二次尝试
这行得通,但我似乎做了 3 次计算。不确定它是否是最有效的方法
cols = paste0("V",1:3)
for(j in 1:3){
set(n,i=NULL,j=cols[j],value = sapply(strsplit(as.character(n$Account_Desc),"[ +]"), "[", j))
}
让我们使用big_n进行基准测试
big_n <- data.table(Subscription_Id = rep(n[,Subscription_Id],1e7),
Account_Desc = rep(n[,Account_Desc],1e7)
)