Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the numbers of occurrences for each group in a tidy data.table? [duplicate]

Tags:

r

data.table

I want to count how many TRUE markers I have for each group in a tidy data.table:

DT <- data.table(      id = c(1   ,1    ,1    ,2   ,2    ,2   ,2   ,2    )
                 , marker = c(TRUE,FALSE,FALSE,TRUE,FALSE,TRUE,TRUE,FALSE))

So I tried DT[marker==TRUE, num_markers := .N, by = id], that outputs:

   id marker num_markers
1:  1   TRUE           1
2:  1  FALSE          NA
3:  1  FALSE          NA
4:  2   TRUE           3
5:  2  FALSE          NA
6:  2   TRUE           3
7:  2   TRUE           3
8:  2  FALSE          NA

Instead, the desired output is:

   id marker num_markers
1:  1   TRUE           1
2:  1  FALSE           1
3:  1  FALSE           1
4:  2   TRUE           3
5:  2  FALSE           3
6:  2   TRUE           3
7:  2   TRUE           3
8:  2  FALSE           3

How do I adjust the code to get the desired output (remove NA for each id and complete with group number of markers?)

like image 836
Fabio Correa Avatar asked Oct 27 '25 06:10

Fabio Correa


2 Answers

Maybe use sum on marker column:

DT[, num_markers := sum(marker), by = id ][]

#    id marker num_markers
# 1:  1   TRUE           1
# 2:  1  FALSE           1
# 3:  1  FALSE           1
# 4:  2   TRUE           3
# 5:  2  FALSE           3
# 6:  2   TRUE           3
# 7:  2   TRUE           3
# 8:  2  FALSE           3
like image 182
zx8754 Avatar answered Oct 29 '25 21:10

zx8754


DT[, num_markers := (.SD[marker, .N]), by = id]

which gives:

> DT
   id marker num_markers
1:  1   TRUE           1
2:  1  FALSE           1
3:  1  FALSE           1
4:  2   TRUE           3
5:  2  FALSE           3
6:  2   TRUE           3
7:  2   TRUE           3
8:  2  FALSE           3
like image 41
Will Avatar answered Oct 29 '25 19:10

Will



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!