This is my dataframe:
Deta <- c("2010-01-29" , "2015-01-29", "2017-01-30")
v <- c(5.1, 3, 4)
a <- c(4.3, 2, 6)
z <- data.frame(Deta,v,a)
I want for columns v and a in each row this formule (last row / row -1). Example ( 4 / 5.1 -1) Could help me ?
I use this mutate_at(-1, c(z[last(z)])/z-1)
but i have an error
This is the output:
Date a v
2010-01-29 -0.21569 0.3953
2015-01-29 0.33333 2.0000
2017-01-30 0.00000 0.00000
We can use :
library(dplyr)
z %>% mutate_at(-1, ~last(.)/. - 1)
#Can also use
#z %>% mutate_at(vars(v, a), ~last(.)/. - 1)
Or in base R :
z[-1] <- lapply(z[-1], function(x) x[length(x)]/x - 1)