# ifelse help with logic

How do I create a script for the following logic:

If Column A = “Monday” AND Column B >= 17, then convert those instances in Column A to “Tuesday” AND those in Column B to 8, otherwise leave all other instances alone.

My attempt:

``````df <- ifelse(df\$ColumnA == “Monday”
& df\$ColumnB >= 17,
df\$ColumnA == “Tuesday”
& df\$ColumnB == 8,
df)
``````

I think the best way of doing this is to create a "flag" column that identifies the rows that meet your requirements, and then use that flag to change the other two columns one at a time.

``````
# create some data
library(tidyverse)

dat = crossing(day = c("Monday", "Tuesday", "Wednesday"),
num = seq(0,30,5))

dat
#> # A tibble: 21 x 2
#>    day       num
#>    <chr>   <dbl>
#>  1 Monday      0
#>  2 Monday      5
#>  3 Monday     10
#>  4 Monday     15
#>  5 Monday     20
#>  6 Monday     25
#>  7 Monday     30
#>  8 Tuesday     0
#>  9 Tuesday     5
#> 10 Tuesday    10
#> # ... with 11 more rows

# solution

dat\$flag = dat\$day == "Monday" & dat\$num >= 17
dat\$day  = ifelse(dat\$flag, "Tuesday", dat\$day)
dat\$num  = ifelse(dat\$flag, 8, dat\$num)
dat\$flag = NULL

dat
#> # A tibble: 21 x 2
#>    day       num
#>    <chr>   <dbl>
#>  1 Monday      0
#>  2 Monday      5
#>  3 Monday     10
#>  4 Monday     15
#>  5 Tuesday     8
#>  6 Tuesday     8
#>  7 Tuesday     8
#>  8 Tuesday     0
#>  9 Tuesday     5
#> 10 Tuesday    10
#> # ... with 11 more rows

# or do it in the tidyverse
dat |>
mutate(flag = day == "Monday" & num >= 17,
day  = if_else(flag, "Tuesday", day),
num  = if_else(flag, 8, num)) |>
select(-flag)
``````

Created on 2021-12-14 by the reprex package (v2.0.1)

1 Like

Thank you so much! I didn’t think of creating a flag column. Worked great

This topic was automatically closed 7 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.