The data that I have is as:
dt_1 cond1 2009-05-04 1 2009-07-04 0
I want to add a variable that has date from a existing variable, if cond1 is 1 else I want set it to missing.
dt_1 cond1 cond1_dt 2009-05-04 1 2009-05-04 2009-07-04 0 NA
if the new variable could retain the format that would be the best.
CodePudding user response:
Supose dat
is your data frame, which has dt_1
and cond1
columns, then you can create the dt_1
column that satisfies your requirement as follows:
dat <- structure(list(dt_1 = structure(c(14368, 14429), class = "Date"),
cond1 = 1:0), row.names = c(NA, -2L), class = "data.frame")
In base
R:
# Assign the value of cond1 column to cond1_dt as a `character date`
dat$cond1_dt <- ifelse(dat$cond1 == 1, as.character.Date(dat$dt_1), NA)
dat
dt_1 cond1 cond1_dt
1 2009-05-04 1 2009-05-04
2 2009-07-04 0 <NA>
# Change the format from a `character date` to a `Date`
dat$cond1_dt <- as.Date(dat$cond1_dt)
dat
dt_1 cond1 cond1_dt
1 2009-05-04 1 2009-05-04
2 2009-07-04 0 <NA>
str(dat)
'data.frame': 2 obs. of 3 variables:
$ dt_1 : Date, format: "2009-05-04" ...
$ cond1 : int 1 0
$ cond1_dt: Date, format: "2009-05-04" ...
In dplyr
:
dat %>% as_tibble() %>%
mutate(cond1_dt = if_else(cond1 == 1, dt_1, as.Date(as.character(NA))))
# A tibble: 2 × 3
dt_1 cond1 cond1_dt
<date> <int> <date>
1 2009-05-04 1 2009-05-04
2 2009-07-04 0 NA