Percentage difference between two events

I have a dataframe that looks like this:

df1 <- 

ID event  CONC
1   1      5
1   2      10
3   1      7
3   2      10

      

For each individual row, I want to calculate the percentage difference in concentration between the two events and add it to a new column.

For example: for ID = 1

diff <- (10-5)*100

      

I need help on how to specify this (CONCrow2-CONCrow1) for every single line. Then I can use the following to apply it by ID:

df2 <- df1 %>%
 group_by(ID) %>%
 mutate (percent = ....)

      

+3


source to share


1 answer


You may try

library(dplyr)
df1 %>% 
    group_by(ID) %>% 
    mutate(percent=100*(CONC-lag(CONC)))

      

Or using base R

transform(df1, percent=ave(CONC, ID, FUN=function(x) 100*c(NA, diff(x))))

      

Or using data.table



library(data.table)
setDT(df1)[, percent := 100*c(NA, diff(CONC)), ID]

      

Update

Based on comments by @Jan Gorecki, shift

this is a new option available in data.table_1.9.5

(devel version)

 setDT(df1)[,percent := 100*(CONC - shift(CONC)), by=ID][]

      

+6


source







All Articles