AK47 - 3 months ago 30
R Question

# ddply transformation (percentage change) in R

I have

`data.frame`
which looks like this:

``````Brand       Year       EUR
Brand1      2015       10
Brand1      2016       20
Brand2      2015       100
Brand2      2016       500
Brand3      2015       25
Brand4      2015       455
...
``````

Also, I attach the code below:

``````library(plyr)
library(dplyr)
library(scales)

set.seed(1992)
n=68

Year <- sample(c("2015", "2016"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:5, n, replace = TRUE, prob = NULL))
EUR <- abs(rnorm(n))*100000

df <- data.frame(Year, Brand, EUR)
``````

I need some additional data transformations (add more columns) for my future research.

Firstly, I calculate positions for labels (for my future chart) and call it
`pos`
:

``````df.summary = df %>% group_by(Brand, Year) %>%
summarise(EUR = sum(EUR)) %>%   #
mutate( pos = cumsum(EUR)-0.5*EUR)
``````

What I want to do is, to calculate
`percentage grow`
for each
`Brand`
in terms of
`Year`
. So I add this line:

``````df.summary = ddply(df.summary, .(Brand), transform,
pChange = (sum(df.summary[df.summary\$Year == "2016",]\$EUR)/
sum(df.summary[df.summary\$Year == "2015",]\$EUR) )-1
)
``````

However, what I get is constant size - growth of all my data frame.

Thanks!

Also, it would be easier if you use `lag`:

``````df.summary %>% group_by(Brand) %>%
mutate(pChange = (EUR - lag(EUR))/lag(EUR) * 100)

# Source: local data frame [10 x 5]
#Groups: Brand [5]
#
#    Brand   Year      EUR      pos   pChange
#   <fctr> <fctr>    <dbl>    <dbl>     <dbl>
#1  Brand1   2015 637896.7 318948.3        NA
#2  Brand1   2016 721944.2 998868.8  13.17573
#3  Brand2   2015 708697.6 354348.8        NA
#4  Brand2   2016 300541.1 858968.2 -57.59248
#5  Brand3   2015 454890.1 227445.1        NA
#6  Brand3   2016 576095.6 742937.9  26.64500
#7  Brand4   2015 305712.0 152856.0        NA
#8  Brand4   2016 174073.3 392748.6 -43.05970
#9  Brand5   2015 589970.7 294985.3        NA
#10 Brand5   2016 518510.2 849225.8 -12.11254
``````

As suggested by @r2evans, if the `Year` is not arranged beforehand,

``````df.summary %>% group_by(Brand) %>% arrange(Year) %>%
mutate(pChange = (EUR - lag(EUR))/lag(EUR) * 100)
``````
Source (Stackoverflow)