BobaFetty91
BobaFetty91

Reputation: 1

Computing a Lag on a Table in R

I have a data table, my_data, with 3 variables, symbol, date, stock price and 141851 observations. The idea is to compute a Lag of 1 day on the stock price, taking care to group by symbol first, otherwise I will have lags computed using values from the previous stock in the data frame.

This are some rows from the table.

Symbol date stock price
MSFT 2019-02-12 106.8100
MSFT 2019-02-13 106.9000
MSFT 2019-02-14 108.2200
APPL 2018-01-02 168.9873
APPL 2018-01-03 168.9579
APPL 2018-01-04 169.7427

I need to to calculate the ratio {price(i)-price(i-1)} / price(i-1) for the whole table. But I cannot shift my it.

I started with R today, so I'm just struggling a lot.

Upvotes: 0

Views: 74

Answers (2)

akrun
akrun

Reputation: 887941

We can also use data.table

library(data.table)
setDT(df1)[, change := round(weight - first(weight))/first(weight) * 100, 2), Chick] 

data

data(ChickWeight)
df1 <- ChickWeight

Upvotes: 2

Magnus Nordmo
Magnus Nordmo

Reputation: 951

Here is an example using a built-in dataset. I recommend dplyr for these calculations. See the cheatsheet.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- data(ChickWeight)

df <- as_tibble(ChickWeight)

df <- df %>% 
  group_by(Chick) %>% 
  mutate(change = (weight-first(weight))/first(weight)*100) %>% 
  mutate(change = round(change,2))

Created on 2020-12-07 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions