I have the following dataframe
date1 date2 Date3 n_var
2017-02-01 2019-02-04 2018-04-01 2
2016-02-01 NA 2017-01-02 3
2017-02-01 2019-02-04 2020-04-01 7
2016-02-01 2019-02-04 2020-04-01 7
And i want this
date1 date2 Date3 price
2017-02-01 2019-02-04 2018-04-01 2
2016-02-01 NA 2017-01-02 3
2017-02-01 2019-02-04 2020-04-01 NA
2016-02-01 2019-02-04 2020-04-01 NA
Rules :
date3 < date1 we pute na in column n_var
date2 is na and date2 < date3 --> we put na in column n_var
otherwise we want the value at each row for n_var
This is my code :
f_NA <- function(nvar)
for(i in 1:nrow(df)) {
df$nvar[i,] <- ifelse((date3<date1), NA,
ifelse(((!is.na(date2)) & date3>date2), NA,df$nvar[i,]))
}
but it does'nt walk?
ifelseis vectorized so no need for a loop. Check if yourdate[1:3]variables are setas.Date, If not convert them and try again - Sotosdf$nvar[i]ordf[i,]instead ofdf$nvar[i,]. - nikodate2isNAthen the second condition does not matter. The result will always beNAbecause the conditional statementdate2<date3is then not possible. - Drjcolumn n_var date2 is na and ....? Your code is doing opposite of what the rule is stated here for the second condition. May be it is a typo. - Drj