Search code examples
rdataframeif-statementtidyverselubridate

Change value of variables for certain months of an R data.frame?


I would like to change the values of Obs and Sim to -1.23 when Month =< 2 & Month >= 11. Seems something simple but am not coming up with any solution.

library(tidyverse)
library(lubridate)

set.seed(123)

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2003-12-31"), by = "day"),
                  Ob = runif(1095,1,5), Sim = runif(1095,1,5)) %>% 
        separate(Date, into = c("Year", "Month", "Day"))

Solution

  • First convert Month to numeric so that you can compare the values. Next you can change the values of Ob and Sim columns to constant when Month <= 2 OR >= 11.

    DF$Month <- as.numeric(DF$Month)
    DF[DF$Month <= 2 |  DF$Month >= 11, c('Ob', 'Sim')] <- -1.23
    

    Or using %in% :

    DF[DF$Month %in% c(1,2,11,12), c('Ob', 'Sim')] <- -1.23
    

    If you want to use dplyr you could do :

    library(dplyr)
    DF <- DF %>% 
           mutate(across(c(Ob, Sim), ~replace(., Month %in% c(1, 2, 11, 12), -1.23)))