I have a data frame and I would like to perform a conditional subtraction/addition of percentage values within different ids using unique codes.
Specifically, I would like to add 10% of code 1 percent values to code 3 percent values, and subtract 10% of code 1 percent values from code 1. The rest of the codes stay the same. Ideally results would be added into a new column.
My question is similar to these two, with some important differences. R ddply with multiple variables and Easiest way to subtract associated with one factor level from values associated with all other factor levels.
I think the best way to do this is plyr, and I have this already however it doesn't work.
df <- data.frame(id=c(rep("113316", 4), rep("113317", 3)), code=c(1,3,4,5,1,3,4), percent=c(0.2571, 0.7257, 0.0114, 0.0057, 0.9596, 0.0058, 0.0857))
df.2 <- ddply(df, .(id, code), transform, percent=(percent*.90[code==1]+percent[code==3] | percent=percent*.90[code==1]-percent[code==1]))
Output would look like this:
id code percent new
113316 1 0.2571 0.23139
113316 3 0.7257 0.75141
113316 4 0.0114 0.01140
113316 5 0.0057 0.00570
113317 1 0.9596 0.86364
113317 3 0.0058 0.10176
113317 4 0.0857 0.08570