Oftentimes, it happens I need to calculate the difference of something between two periods. If each row represents a period, the fastest thing to do is to lag the variable you need to perform calculations on.
In R, the lag() function from the stats package is an option, but you’ll notice it won’t work in data frames.
There’s a manual, not so elegant solution. For example, I can create a lagged variable with an offset of one simply by adding an NA in front of a vector and removing the last item. The leading variable with an offset of one is completely analogous.
library(data.table)
dt <- data.table(base = seq(1,10,1))
dt$lagged_manual <- c(NA,dt$base[1:(nrow(dt)-1)])
dt$leading_manual <- c(dt$base[2:nrow(dt)],NA)
See, not so elegant. However, the data.table package offers some really nice functionalities to create leading and lagged variables. The shift() function provides lagging/leading capabilities with an easy to use interface.
dt[,lagged_base := shift(base, 1, type = 'lag')]
dt[,leading_base := shift(base, 1, type = 'lead')]
By the way, if you’re having trouble understanding some of the code and concepts, I can highly recommend “An Introduction to Statistical Learning: with Applications in R”, which is the must-have data science bible. If you simply need an introduction into R, and less into the Data Science part, I can absolutely recommend this book by Richard Cotton. Hope it helps!
Great success!
Pingback: facebook comments blog seo
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Абсолютно все трендовые события часового искусства – новые коллекции лучших часовых компаний.
Все коллекции хронографов от бюджетных до супер премиальных.
https://podium24.ru/
Несомненно трендовые события индустрии.
Все новости всемирных подуимов.
Модные дома, торговые марки, высокая мода.
Свежее место для трендовых людей.
https://fashion5.ru/
médicaments expédiée rapidement et discrètement almus Caldono Pharmacies en ligne
offrant médicaments en France
nemo kz отзывы, itell-kz где можно обменять мелочь на купюры,
где можно обменять монеты на купюры павлодар қазақ орфографиясының
тарихы, қазақ орфографиясының негізгі ережелері туралы қысқаша конспект жена
бурундук-хана, жена касым хана айша
ерте жастан көмек көрсету бағдарламалары, ерте
жастан түзете дамыту технологиялары captain morgan spiced gold отзывы, виски
капитан блэк менің құқығым бар эссе, менің
құқығым шығарма алаш арыстары кластер,
алаш қайраткерлері мәлімет