Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ratio with a reference value by ID and year using R

I have a panel data with fields – ID, Value, Year, Qtr. I need to compute a ratio field for each ID by dividing the current period value with the starting period value. So, for ID = 1, the ratio would be 10/10, 12/10, and 13/10. Same for ID = 2.

ID  Value   Year    Qtr Ratio
1   10  2010    1   1
1   12  2010    2   1.2
1   13  2010    3   1.3
2   15  2012    1   1
2   22  2012    2   1.466666667
2   10  2012    3   0.666666667
2   16  2012    4   1.066666667

Panel Data

I checked few suggestions such as How to look up previous values in an R data frame by ID and year? and Calculating ratios by group with dplyr – but am unable to code this. Kindly guide. Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

At the risk of overlooking something obvious, I would use ave:

df <- data.frame(ID = c(1,1,1,2,2,2,2),
                 Value = c(10,12,13,15,22,10,16),
                 Year = c(rep(c(2010, 2012), each = 3), 2012),
                 Qtr = c(rep(1:3, 2), 4))

# df$Result = 
with(df, ave(x= Value, ID, FUN = \(x) x / x[[1L]]))
#> [1] 1.0000000 1.2000000 1.3000000 1.0000000 1.4666667 0.6666667 1.0666667

Created on 2023-12-12 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading