Replace values of an R data.frame between certain Dates?

Viewed 455

I have the following data.frame and would like to replace values of Flow to -1 for the year 2001. Any help would be appreciated.

library(lubridate)
library(tidyverse)

set.seed(123)

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "day"),
                       Flow = runif(1826,1,5))
2 Answers

Extract the year from 'Date' column, check if it is equal to 2001, and replace with -1

library(lubridate)
library(dplyr)
DF <- DF %>% 
   mutate(Flow = replace(Flow, year(Date) == 2001, -1))

Or using base R - get the 'Year' part by standard use of format and do the check with '2001' to create a logical vector and assign those 'Flow' elements to -1

DF$Flow[format(DF$Date, '%Y') %in% '2001'] <- -1

Base R option -

Use grepl/grep to find the rows which start with 2001, and change the Flow values to -1.

DF$Flow[grep('^2001', DF$Date)] <- -1
DF
Related