I have this following code:
library(tidyverse)
library(tsibble)
time <- c("2020 01", "2020 02", "2020 03", "2020 04", "2020 05", "2020 06",
"2020 01", "2020 02", "2020 03", "2020 04", "2020 05", "2020 06",
"2020 01", "2020 02", "2020 03", "2020 04", "2020 05", "2020 06",
"2020 01", "2020 02", "2020 03", "2020 04", "2020 05", "2020 06")
state <- c(rep("CA", 6), rep("PA", 6), rep("NY", 6), rep("WI", 6))
values <- rnorm(24)
dataf <- data.frame(time, state, values)
dataf <- dataf %>%
mutate(time = yearmonth(time)) %>%
as.data.frame()
dataf_tsible <- as_tsibble(dataf, index = time, key = state)
Now, I want to remove the values in the variable values from March to May 2020.
This works:
dataf_tsible$values[dataf_tsible$time== yearmonth("2020 Mar")] <- NA
dataf_tsible$values[dataf_tsible$time== yearmonth("2020 Apr")] <- NA
dataf_tsible$values[dataf_tsible$time== yearmonth("2020 May")] <- NA
But is there any better and more efficient way to do that without changing the time class?
You could carryout a
mutate
to replace selected values withNA
prior to creating thetsibble
.Created on 2023-10-23 with reprex v2.0.2