Home > other >  add months to a date ifelse
add months to a date ifelse

Time:12-02

I want to add months to a date by conditition. That means if my ISO column is ET I want to add 92 month.

When I only run this code, i recieve the dates I want.

ymd(paste(comb_extract_all$hv007, comb_extract_all$hv006, "01", sep = "-")) %m % months(92)

first lines of my output:

 [1] "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01"
 [9] "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01"
[17] "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01"
[25] "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01" "2011-04-01"

But if I use it in an ifelse statement, it will returns numbers

comb_extract_all$date <- ifelse(comb_extract_all$ISO == "ET", 
                                ymd(paste(comb_extract_all$hv007, comb_extract_all$hv006, "01", sep="-")) %m % 
                                  months(92),
                                ymd(paste(comb_extract_all$hv007, comb_extract_all$hv006, "01", sep="-")))

My dput output with the most important columns is as follows (where you can see the "wrong" date column):

dput(comb_extract_all[1:5,c(1,5,6,23,24)])
structure(list(hhid = c("        1 27", "        1 27", "        1 27", 
"        1 27", "        1 67"), hv006 = c(8, 8, 8, 8, 8), hv007 = c(2003, 
2003, 2003, 2003, 2003), ISO = c("ET", "ET", "ET", "ET", "ET"
), date = c(15065, 15065, 15065, 15065, 15065)), row.names = c("ETPR61SV.1", 
"ETPR61SV.2", "ETPR61SV.3", "ETPR61SV.4", "ETPR61SV.5"), class = "data.frame")

CodePudding user response:

One option to avoid the implicit conversion to numerics would be to switch to dplyr::if_else:

library(lubridate)
library(dplyr)

comb_extract_all$date <- ymd(paste(comb_extract_all$hv007, comb_extract_all$hv006, "01", sep = "-"))

comb_extract_all$date <- dplyr::if_else(comb_extract_all$ISO == "ET",
  comb_extract_all$date %m % months(92),
  comb_extract_all$date
)

comb_extract_all
#>                    hhid hv006 hv007 ISO       date
#> ETPR61SV.1         1 27     8  2003  ET 2011-04-01
#> ETPR61SV.2         1 27     8  2003  ET 2011-04-01
#> ETPR61SV.3         1 27     8  2003  ET 2011-04-01
#> ETPR61SV.4         1 27     8  2003  ET 2011-04-01
#> ETPR61SV.5         1 67     8  2003  ET 2011-04-01

CodePudding user response:

Try

library(tidyverse)
comb_extract_all$date <- 
  if_else(comb_extract_all$ISO == "ET", 
        (ymd(paste(comb_extract_all$hv007,
        comb_extract_all$hv006,"01", 
        sep = "-")) %m % months(92)),                                    
  (ymd(paste(comb_extract_all$hv007,
            comb_extract_all$hv006,"01", 
            sep = "-"))))

  • Related