0

I have a group and persons in each group. and an indicator. How to count indicator per each group for each person element?

     group  person   ind
       1       1      1
       1       1      1
       1       2      1
       2       1      0
       2       2      1
       2       2      1

output so in the first group 2 persons have 1 in ind, and second group one person so

      group  person   ind.   count  
       1       1      1        2
       1       1      1        2
       1       2      1        2
       2       1      0       1
       2       2      1        1
       2       2      1        1
  • 2
    Possible duplicate of [How to sum a variable by group](https://stackoverflow.com/questions/1660124/how-to-sum-a-variable-by-group) – NelsonGon Aug 03 '19 at 12:03

2 Answers2

1

Could do:

library(dplyr)

df %>%
  group_by(group) %>%
  mutate(
    count = n_distinct(person[ind == 1])
  )

Output:

# A tibble: 6 x 4
# Groups:   group [2]
  group person   ind count
  <int>  <int> <int> <int>
1     1      1     1     2
2     1      1     1     2
3     1      2     1     2
4     2      1     0     1
5     2      2     1     1
6     2      2     1     1

Or in data.table:

library(data.table)

setDT(df)[, count := uniqueN(person[ind == 1]), by = group]
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
1

An option using base R

df1$count <-  with(df1, ave(ind* person, group, FUN = 
          function(x) length(unique(x[x!=0]))))
df1$count
#[1] 2 2 2 1 1 1
akrun
  • 874,273
  • 37
  • 540
  • 662