Subtraction based on multiple groups in R -


i have following df , looking populate variable 3 based off country , branch , m1 of variable 1 divided m1 - 1 of variable 2.

so example, row 1 give n/a since there no m1 - 1, m2 result variable 3 82/992 = 8.27%. best way on doing this?

i can think of creating table move variable 2 month needs subtracted , merge current table using dplyr.

i wondering if there easier way it?

country branch  month   variable 1  variable 2  variable 3 x             12      41          992         n/a x             1       82          693         8.27% x             2       40          686         5.77% x       b       12      84          793         n/a x       b       1       6           947         0.76% x       b       2       48          809         5.07% y             12      78          546         n/a y             1       16          796         2.93% y             2       50          945         6.28% y       b       12      57          862         n/a y       b       1       73          689         8.47% y       b       2       1           971         0.15% 

we can use

library(data.table) setdt(df1)[, variable3 := as.character(round(100*variable1/shift(variable2), 2)),            = .(country, branch)            ][!is.na(variable3), variable3 := paste0(variable3, "%")][] 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -