group_ID <- c("a","a","a","a","a","b","b","b","b","b","b","b","b")
class <- c("p","q","q","q","q","p","p","p","q","q","q","q","q")
var1 <- c(3,1,1,1,1,3,2,1,1,2,2,4,1)
my_table <- data.frame(group_ID,class,var1)
I have the following table.
group_ID class var1
a p 3
a q 1
a q 1
a q 1
a q 1
b p 3
b p 2
b p 1
b q 1
b q 2
b q 2
b q 4
b q 1
I want to create a new column by dividing the median of var1 of class p by the median var1 of the q class for each group. The expected output is shown below.
group_ID class var1 var1_ratio
a p 3 3
a q 1 3
a q 1 3
a q 1 3
a q 1 3
b p 3 1
b p 2 1
b p 1 1
b q 1 1
b q 2 1
b q 2 1
b q 4 1
b q 1 1
Link: This question seems to be the most similar to mine and I tried using group_by() and mutate_each() as below but I can't get it to work.
my_table <- my_table %>%
group_by(group_ID,class) %>%
mutate_each(funs(./median(.[class == "p"])), var1)
Also I tried : Link1 Link2 Link3
Thanks!