So I need to calculate the percent difference of all combinations of values in column y
. For example the difference between B 1 and B 2. Then the Difference between B 1 and B 3, and so on for all combinations of B. Then the same thing for all combinations of D.
Here is some example data...
structure(list(Levelname = c("B 1", "B 2", "B 3",
"B 4", "D 1", "D 2", "D 3", "D 4"), y = c(0.679428655093332,
1.07554328679719, 0.883000346050764, 0.791772867506205, 0.538143790501689,
0.805122127560562, 0.591353204313314, 0.795225886492002), fill = c("midnightblue",
"dodgerblue4", "steelblue3", "lightskyblue", "midnightblue",
"dodgerblue4", "steelblue3", "lightskyblue"), species = c("White Grunt",
"White Grunt", "White Grunt", "White Grunt", "White Grunt", "White Grunt",
"White Grunt", "White Grunt")), row.names = c(NA, -8L), class = "data.frame")
My ideal output would be a dataframe with some sort of identifier like
Pair Percent Difference
B 1 - B 2 45.142
B 1 - B 3 .....
B 1 - B 4 .....
B 2 - B 3 .....
B 2 - B 4 .....
B 3 - B 4 .....
D 1 - D 2 .....
D 1 - D 3 .....
D 1 - D 4 .....
D 2 - D 3 .....
D 2 - D 4 .....
D 3 - D 4 .....
where ..... are the percent differences
I don't care about the differences between B and D. Also I'm trying to get better at functions, for
loops, and the apply
functions of r, so if answers can use those or a variety of those that would be great.
I tried to look at these answers but I couldn't figure it out...
Loops in R - Need to use index, anyway to avoid 'for'? How can I calculate the percentage change within a group for multiple columns in R?
The 45.142
I calculated using this
|B1−B2|/[(B1+B2)/2]×100=?
=|0.67942865509333−1.0755433|/[(0.67942865509333+1.0755433)/2]×100
=|−0.39611464490667|/[1.7549719550933/2]×100
=0.39611464490667/0.87748597754667×100
=0.45142×100
=45.142% difference