Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summarize (count/freq) by treatment type where individuals could receive both treatments

Tags:

r

dplyr

Say we have this data:

dat<-data.frame(id=c(1,1,2,2,3,4,4,5,6,6),Rx=c(1,2,1,2,1,1,1,2,2,2))

   id Rx
1   1  1
2   1  2
3   2  1
4   2  2
5   3  1
6   4  1
7   4  1
8   5  2
9   6  2
10  6  2

Where Id is the subject id, and Rx is the treatment they received. So, there are repeated observations and the treatment may or may not be consistent per subject.

I want to be able to summarize how many subjects only received Rx 1, only received Rx 2, and how many received Rx 1 and 2.

I'd prefer a dplyr solution, but data.table and base R would be fine too. I thought something like:

dat %>%
  group_by(id,Rx) %>%
  unique() %>%
  ...something

The end result should be something like:

  Rx    Count
   1        2
   2        2
Both        2

Thanks!

like image 334
Andrew Taylor Avatar asked Feb 04 '15 16:02

Andrew Taylor


1 Answers

Here's another generalized solution

library(dplyr)
dat %>%
  group_by(id) %>%
  summarise(indx = toString(sort(unique(Rx)))) %>%
  ungroup() %>%
  count(indx)

# Source: local data table [3 x 2]
# 
#   indx n
# 1 1, 2 2
# 2    1 2
# 3    2 2

With data.table, similarly

library(data.table)
setDT(dat)[, .(indx = toString(sort(unique(Rx)))), id][ , .N, indx]
like image 89
David Arenburg Avatar answered Sep 30 '22 07:09

David Arenburg