Home > Mobile >  replace multiple values using ifelse
replace multiple values using ifelse

Time:09-28

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:

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()

CodePudding user response:

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

CodePudding user response:

You could use gsub.

transform(df, date=gsub('1/0', '01/01', 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

Or more explicitly:

transform(df, date=stringi::stri_replace_all_regex(date,
                                                   pattern=c("1/0/2000", "1/0/2005"),
                                                   replacement=c("01/01/2000", "01/01/2005"),
                                                   vectorize=FALSE
))
#   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
  • Related