Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace multiple values using ifelse

Based on the code and data below how can I replace values in the date column with new values using ifelse.

Error:

Warning message:
Problem while computing `date = ifelse(...)`.
ℹ longer object length is not a multiple of shorter object length 

Data and code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df = structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8), date = c("1/0/2000", 
"1/0/2005", "1/0/2005", "1/0/2005", "1/0/2005", "1/0/2005", "1/0/2005", 
"1/0/2005")), class = "data.frame", row.names = c(NA, -8L))

desired = structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8), date = c("01/01/2000", 
"01/01/2005", "01/01/2005", "01/01/2005", "01/01/2005", "01/01/2005", "01/01/2005", 
"01/01/2005")), class = "data.frame", row.names = c(NA, -8L))

df = df%>% mutate(date = ifelse(date == c("1/0/2000", "1/0/2005"), 
                                                   c("01/01/2000", "01/01/2005"), 
                                                   date)) # works if I run ifelse twice once for `1/0/2000` and once for `1/0/2005` without c()

>Solution :

You could use case_when instead of ifelse

df %>% mutate(date = case_when(date == "1/0/2000" ~ "01/01/2000", 
                               date == '1/0/2005' ~ "01/01/2005", 
                               TRUE ~ date))
#>   id       date
#> 1  1 01/01/2000
#> 2  2 01/01/2005
#> 3  3 01/01/2005
#> 4  4 01/01/2005
#> 5  5 01/01/2005
#> 6  6 01/01/2005
#> 7  7 01/01/2005
#> 8  8 01/01/2005
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading