I'm trying to use the following R data.table to create multiple columns out of the "Ref" field:
library(data.table)
(dt= data.table(Ref = c("R", "STOP", "STOP_TS", "P", "M", "STOP_P_R"),
Qty= c(2,4,6,8,10,12)))
The new columns should be based on single ref only (e.g. "STOP" and "TS) as opposed to combined ref (e.g. "STOP_TS"). Once a single ref is identified by using "_" separator, the new column should take the value of the "Qty" field, otherwise it should be zero. The desired output should look like this:
#Desired Output
(desired=data.table(
Ref= c("R", "STOP", "STOP_TS", "P", "M", "STOP_P_R"),
Qty= c(2,4,6,8,10,12),
R = c(2,0,0,0,0,12),
STOP= c (0,4,6,0,0,12),
TS= c(0,0,6,0,0,0),
P= c(0,0,0,8,0,12),
M=c(0,0,0,0,10,0)))
The problem I have with my approach is that the regex part wrongly matched "P" when looking at "STOP", since it doesn't specify to match for complete 'words'.
library(foreach)
library(data.table)
ref<-unlist(unique(dt$Ref)) #extract unique combined ref
ref2<-strsplit(ref, "_") #split ref by using "_"
ref3<-unique(unlist(ref2)) #extract unique single ref (columns to create)
dt2<-foreach(i=1:length(ref3), .combine='cbind')%do%{
eval(parse(text=paste0("tmp<-ifelse( grepl(ref3[i], dt$Ref), dt$Qty,0)")))
data.table(tmp)
}
names(dt2)<-ref3
(dt3=cbind(dt,dt2))
As a way to check, the sum of column "P" should be 20 (8 for Ref="P" and 12 for Ref="STOP_P_R").
I'd appreciate any comments or suggestions on this.
dl