#DT
NO GROUP KEY TYPE <--- Create this column
12-19 N 1701 INN
10-20 N 1602 INN
13 P 1501John BANK
14 R 1408Mary POOL
15 G 1408Peter PARK
19 K 1408Paul BANK
25 P 1708 OTHER
36 R 1503 OTHER
DT[,"TYPE":= RefDT[match(DT$KEY,Ref$KEY),2]]
# RefDT like below :
KEY TYPE
1609TOM PARK
1501John BANK
1408Mary POOL
1408Peter PARK
1408Paul BANK
1309Sue POOL
*如果Col:No包含“-”,则TYPE为“ INN”。
DT[,TYPE:= ifelse(grepl("-",DT$No),"INN",TYPE)]
*如果Col:GROUP为“ P”或“ R”,TYPE为“ Other”,则步骤1规则将覆盖此规则。这就是为什么即使某些行在Col:GROUP中也包含“ P”或“ R”的原因,但是如果\ KEY的有效键有效,它们的TYPE不会改变。
DT <- DT[is.na(TYPE),] %>% mutate(TYPE = ifelse(grepl("P|R",GROUP),"OTHER",TYPE)) %>%
rbind(DT[!is.na(TYPE),])
由于实际数据集包含200万行,因此我需要更快 实现此的方法。欢迎使用任何有效的脚本来 总结了三个笨拙的脚本,它们只能创建一列。
答案 0 :(得分:2)
如果我们使用的是data.table
,请通过'KEY'和'RefDT'指定(:=
-与mutate
类似)的'RefDT'中的'TYPE'进行联接。在“ DT”中创建“ TYPE”列。如果没有匹配项,则默认情况下将使用NA
进行填充。然后通过在i
中指定逻辑条件来进行后续分配(grepl("-", NO)
-在“否”列中检查-
,在“组”中检查“ P”或“ R”其中“ TYPE”为NA
)
setDT(DT)[RefDT, TYPE := TYPE, on = .(KEY)]
DT[grepl("-", NO), TYPE := "INN"
][is.na(TYPE) & grepl("P|R", GROUP), TYPE := "OTHER"][]
# NO GROUP KEY TYPE
#1: 12-19 N 1701 INN
#2: 10-20 N 1602 INN
#3: 13 P 1501John BANK
#4: 14 R 1408Mary POOL
#5: 15 G 1408Peter PARK
#6: 19 K 1408Paul BANK
#7: 25 P 1708 OTHER
#8: 36 R 1503 OTHER
DT <- structure(list(NO = c("12-19", "10-20", "13", "14", "15", "19",
"25", "36"), GROUP = c("N", "N", "P", "R", "G", "K", "P", "R"
), KEY = c("1701", "1602", "1501John", "1408Mary", "1408Peter",
"1408Paul", "1708", "1503")), .Names = c("NO", "GROUP", "KEY"
), row.names = c(NA, -8L), class = "data.frame")
RefDT <- structure(list(KEY = c("1609TOM", "1501John", "1408Mary", "1408Peter",
"1408Paul", "1309Sue"), TYPE = c("PARK", "BANK", "POOL", "PARK",
"BANK", "POOL")), .Names = c("KEY", "TYPE"),
class = "data.frame", row.names = c(NA,
-6L))