'Calculate percent difference conditioned on matching levels of a factor [duplicate]

I have a data frame structured like this:

dat<- data.frame(Treatment= c(rep("treat1", 3), rep("treat2", 3), rep("control",3)), 
                 Plant= rep(c("A", "B", "C"), 3),
                 val= c(10,  6,  5,  9,  5,  6,  4,  2,  7))

For each level of Treatment and Plant I need to find the corresponding Plant in the control group of the Treatment variable. Then, calculate the percent difference between the two values. For example, Treatment=="treat1" & Plant== "A" matches with Treatment=="control" & Plant== "A". The percent difference between the two follows this calculation: (10-4)/((10+4)/2))= +85.71%.

The result output for this example would be:

res<- data.frame(Treatment= c(rep(1, 3), rep(2, 3)), 
             Plant= rep(c("A", "B"), 3),
             per_diff= c((10-4)/(sum(10,4)/2)*100, (6-2)/(sum(6,2)/2)*100,  (5-7)/(sum(5,7)/2)*100,
             (9-4)/(sum(9,4)/2)*100, (5-2)/(sum(5,2)/2)*100, (6-7)/(sum(6,7)/2)*100))


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source