VJ D
VJ D

Reputation: 177

Count number of groups with single rows in r data table

I have a data table with grouping. I want to count the number groups where only single row is present.

dt[ , count := .N, by = .(name, type)]

This give me count of rows in each group, By I need the total count of groups which are having single row in it.

Upvotes: 1

Views: 538

Answers (3)

akrun
akrun

Reputation: 887951

We can use

library(dplyr)
dt %>%
    count(name, type) %>%
    summarise(n = sum(n ==1))

Or an option with data.table

dt[, sum(table(paste(name, type)) == 1)]

Upvotes: 1

Samuel Allain
Samuel Allain

Reputation: 478

What about

table(dt[ , .(count = .N), by = .(name, type)][, count]) ?

@ronakshah 's new answer only works in this setup where 1 line = 1 group because it recycles the count for all lines so that you count the number of lines which are in a one-element group which is different that the number of groups with one line.

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

If you need to count only the groups which has count as 1 you can do

library(data.table)
nrow(dt[ , .(count := .N), by = .(name, type)][count == 1])

Or :

sum(dt[ , .(count := .N), by = .(name, type)]$count == 1)

If you want to subset the rows where number of rows is 1 in a group you can do

dt[, .SD[.N == 1], (name, type)]

and using nrow on this would give you again count of groups.

Upvotes: 3

Related Questions