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

How to change row values with calculation in R

I need some help with my data frame (df) in R. I need to transform existing row values with some calculation and I don’t know how to apply it to every row I need. I have gross domestic product and I need to change it obsValues with calculation that includes CPI row values : (GDP/CPI)*100. The most difficult thing here is that GDP and CPI are in rows not in columns…

My dataframe looks like this:

enter image description here

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

enter image description here

Thanks in advance!

>Solution :

We may do

library(dplyr)
library(stringr)
df1 <- df1 %>% 
       group_by(obsTime) %>% 
       mutate(obsValue = replace(obsValue, 
        SUBJECT_DEF == "Gross domestic product", 
        obsValue[SUBJECT_DEF == "Gross domestic product"]/
         obsValue[str_detect(SUBJECT_DEF, "CPI:")] * 100)) %>%
      ungroup
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