Format Date in ifelse function

I have two columns (symtpom_onset; and test_positive.
So now I want to transfer the information of test_positive to symptom_onset column. With condition, if symptom_onset is missing value.

And here my code

mutate(symptom_onset = ifelse(is.na(symptom_onset),(test_positive), symptom_onset))

=> the problem is the result of symptom_onset column was show different format date.
How can I fit it?

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

1 Like

Error1
In here, I have A, B colums by date. my concept is if A missing value then B - 21. I wrote the function:
data2 <- data1 %>% mutate(A=ifelse(is.na(A)==TRUE, B-21, B))
However, the result showed not format date by A colums.
Pls help me to solove?

Hi @Drdinhluong,
Here is how to use ifelse in the situation you describe:

suppressPackageStartupMessages(library(tidyverse))
df <- data.frame(A = c(NA, "2021-04-09", NA, "2021-04-21", NA),
                 B = c("2021-05-03", NA, "2021-05-05", "2021-05-02", "2021-05-05"))
df
#>            A          B
#> 1       <NA> 2021-05-03
#> 2 2021-04-09       <NA>
#> 3       <NA> 2021-05-05
#> 4 2021-04-21 2021-05-02
#> 5       <NA> 2021-05-05

# Check that the ifelse logic is correct
ifelse(is.na(df$A), df$B, df$A)
#> [1] "2021-05-03" "2021-04-09" "2021-05-05" "2021-04-21" "2021-05-05"

# Make changes to dataframe
df %>% 
  mutate(A = ifelse(is.na(A), B, A) ) -> df
df
#>            A          B
#> 1 2021-05-03 2021-05-03
#> 2 2021-04-09       <NA>
#> 3 2021-05-05 2021-05-05
#> 4 2021-04-21 2021-05-02
#> 5 2021-05-05 2021-05-05

Created on 2021-06-18 by the reprex package (v2.0.0)

As @andresrcs suggests, your Reproducible Example should include some relevant data in text form (not just a screenshot from your monitor) because otherwise in order to help you someone has to type that data in to demonstrate a solution.
HTH

1 Like


Hi DavoWW

Thank for your support.
I make at step # Check that the ifelse logic is correct
so the result is not logic, BUT incuba.data1 is data.frame. I checked it
Pls, help me.

maybe sometimes when A is na, B might also be NA , so replacing A with B still gives you NA's ?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.