My data looks something like this (a simplified version):
df <- read.table(text="cohort,med1,med2,med3,meq1,meq2,meq3
a,drugA,drugB,NA,4.3,1.9,NA
b,drugB,drugC,drugA,2.1,2.0,4.5
a,drugC,NA,NA,2.0,NA,NA
a,drugA,drugB,NA,5.5,3.6,NA
b,drugB,drugA,drugC,4.9,4.1,4.1", sep=",", header=TRUE)
## > df
## cohort med1 med2 med3 meq1 meq2 meq3
## 1 a drugA drugB <NA> 4.3 1.9 NA
## 2 b drugB drugC drugA 2.1 2.0 4.5
## 3 a drugC <NA> <NA> 2.0 NA NA
## 4 a drugA drugB <NA> 5.5 3.6 NA
## 5 b drugB drugA drugC 4.9 4.1 4.1
Each of the med values is paired with each of the meq values (e.g. the value of meq1 is the value for that instance of med1). How can I restructure the data to be grouped by med and by cohort and get both the count of med and average value of meq?
For example:
cohort med meq
a drugA 4.9
a drugB 2.75
a drugC 2.0
b drugA 4.3
b drugB 4.5
b drugC 3.05