Home > Software design >  How to change row values with calculation in R
How to change row values with calculation in R

Time:11-13

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

enter image description here

Thanks in advance!

CodePudding user response:

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
  • Related