show values as difference from previous in R

Posted on: December 18, 2017 Posted by: Guy Manova Comments: 0

show values as difference from previous in R

Excel show values as difference from previous in R

In this short tutorial learn how to emulate Excel show value as difference from previous in R.

In Excel

difference from previous in R

difference from previous in R

In R

# pre-session options

rm(list = ls())
# getwd()
# setwd(“your preferred file folder”)

df <- read.csv(“https://www.dropbox.com/s/uhp0ne0rdxk9k7r/stocks.csv?dl=1”)
write.csv(df, “stocks.csv”)

library(dplyr)
library(tidyr)

df1 <- df %>%
select (Date, Adj.Close, stock) %>%
group_by(stock) %>%
mutate(DiffPrev = Adj.Close – lag(Adj.Close)) %>%
mutate(DiffPrevPercent = (Adj.Close – lag(Adj.Close))*100/lag(Adj.Close))

difference from previous in R

difference from previous in R

 

 

 

 

 

Leave a Reply:

Your email address will not be published. Required fields are marked *