ifelse() function - refer to the following day
A base R
approach would be to create a copy of the 'return' as new column 'return_sub', then using the numeric index ('i1'), assign the value to NA
i1 <- which(df$return > 3.5)
df$return_subsequent_day <- df$return
df$return_subsequent_day[pmin(i1 +1, nrow(df))] <- NA
df$return_subsequent_day
#[1] 1.0 2.5 2.0 3.0 5.0 NA NA 9.0 NA 2.0
using lag
and mutate
from dplyr
. With lag we compare the return
-value of the previous row with 3.5
: if it's bigger or equal we take the NA
, and if it's smaller we take the return value of the current row
library(dplyr)
df <- df %>% mutate(return_subsequent_day = ifelse(lag(return, default = 0) >= 3.5, NA, return))
output:
# A tibble: 10 x 3
date return return_subsequent_day
<date> <dbl> <dbl>
1 2019-03-14 1 1
2 2019-03-15 2.5 2.5
3 2019-03-16 2 2
4 2019-03-17 3 3
5 2019-03-18 5 5
6 2019-03-19 6.5 NA
7 2019-03-20 1 NA
8 2019-03-21 9 9
9 2019-03-22 3 NA
10 2019-03-23 2 2
Simple solution using ifelse
df$return_sub_day <- ifelse(dplyr::lag(df$return) > 3.5, NA ,df$return)
df$return_sub_day[1] <- df$return[1]