I have a datatable with 3 categorical variables: primarydx, NumDx, and ContractType.
primarydx <- rep(c("AB","MT"),10)
NumDx <- rep(c(1,2,3), length.out=20 )
ContractType <- rep( c("W","L","W","W","W") , length.out=20)
SecDx3 <- data.table(primarydx, NumDx, ContractType)
I want to calculate the percentage of records of each ContractType within primarydx and NumDx. The following code works:
Num <-SecDx3[ , .(n=.N), by=.(primarydx, NumDx, ContractType)]
denom <- SecDx3[ , .(d=.N), by=.(primarydx, NumDx)]
pct <- merge(Num,denom)
pct[,pct:=n/d][]
Is there a better way?
I did find something like:
SecDx3[,{
d =.N
.SD[, .(pct = .N/d), by=.(primarydx, NumDx, ContractType)]
}, by=.(primarydx, NumDx)]
but this returns an error "The items in the 'by' or 'keyby' list are length (1,1,20). Each must be same length as rows in x or number of rows returned by i (20)." which I don't understand.
Thanks for your help,
David
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)