Chris
Chris

Reputation: 1237

Calculate percentage summaries in data.table

If this is my dataset:

library(data.table)    
dt <- data.table(
  record=c(1:20),
  area=rep(LETTERS[1:4], c(4, 6, 3, 7)), 
  score=c(1,1:3,2:3,1,1,1,2,2,1,2,1,1,1,1,1:3),
  cluster=c("X", "Y", "Z")[c(1,1:3,3,2,1,1:3,1,1:3,3,3,3,1:3)]
)

What is the best way using data.table to calculate percentage summaries like this:

prop.table(table(dt$area, dt$score), 1)*100

However, I would also want more flexibility in the inputs of this summary. For example, including only records that belong to cluster 'X' or clusters 'Y' and 'Z')

Upvotes: 0

Views: 1843

Answers (1)

Vladimir Volokhonsky
Vladimir Volokhonsky

Reputation: 155

dt[,.N,by=list(area,score)][,perc:=100*N/sum(N),by=area][,.SD]

and dcast.data.table if you need

Upvotes: 2

Related Questions