dataframe - Compute values relative to specific factor in R data frame -
i have data frame in r of following form:
bc solvopt istrng tsolv epb 1 10 1 0 0.10 -78.1450 2 10 1 1 0.15 -78.7174 3 10 1 10 0.14 -78.7175 4 10 1 100 0.12 -78.7184 5 10 1 1000 0.09 -78.7232 6 10 1 2 0.15 -78.7175 7 10 1 20 0.14 -78.7176 8 10 1 200 0.12 -78.7192 30 10 2 0 0.10 -78.1450 31 10 2 1 0.11 -78.7174 32 10 2 10 0.11 -78.7175 33 10 2 100 0.10 -78.7184 34 10 2 1000 0.13 -78.7232 35 10 2 2 0.11 -78.7174 36 10 2 20 0.10 -78.7176 37 10 2 200 0.10 -78.7192 59 10 3 0 0.16 -78.1450 60 10 3 1 0.23 -78.7174 61 10 3 10 0.21 -78.7175 62 10 3 100 0.19 -78.7184 63 10 3 1000 0.17 -78.7232 64 10 3 2 0.22 -78.7175 65 10 3 20 0.21 -78.7176 66 10 3 200 0.18 -78.7192 88 10 4 0 0.44 -78.1450 89 10 4 1 14.48 -78.7162 90 10 4 10 12.27 -78.7175 91 10 4 100 1.23 -78.7184 92 10 4 1000 0.44 -78.7232 93 10 4 2 14.52 -78.7172 94 10 4 20 6.16 -78.7176 95 10 4 200 0.62 -78.7192
i want add column frame shows relative error in epb each value of bc , istrng relative solvopt=3.
for example, compute relative difference in epb @ each row subtract epb value of corresponding row same value of bc , istrng solvopt=3.
is there easy way short of splitting multiple data frames (for each solvopt) , remunging together?
the end goal generate plots of relative error vs istrng each value of bc using qplot.
if merge
subset solvopt==3
against main data on both bc
, istrong
, , subtract difference, should result want, e.g.:
newdat <- merge(dat,dat[dat$solvopt==3,c("bc","istrng","epb")], by=c("bc","istrng")) newdat$diff <- with(newdat, epb.x - epb.y)
...or in 1 fell swoop using match
, interaction
:
dat$diff <- dat$epb - dat[dat$solvopt==3,"epb"][match( with(dat, interaction(bc,istrng) ), with(dat[dat$solvopt==3,], interaction(bc,istrng) ) )]