changing values with if else

raw data:

name direction type
Anna up        single
Liam up        divorced
Ryan down      single
Aida updown    married
Rita down      single
Lita downup    bachelorette

if the direction "above" your row contains the word "down" (as is the case with Aida and Lita), and your row contains the letters "up" then we must 1)change direction to "down" and 2)the type must also be changed to "CHANGED"
is there an easy way to do this? thank you.

what I want:

name direction type         direction_new     type_new
Anna up        single            up            single
Liam up        divorced          up            divorced
Ryan down      single           down           single
Aida updown    married          down           CHANGED
Rita down      single           down           single
Lita downup    bachelorette     down           CHANGED

Hi!
Here is my solution using the tidyverse.

df <- data.frame(
          name = c("Anna", "Liam", "Ryan", "Aida", "Rita", "Lita"),
          direction = c("up", "up", "down", "updown", "down", "downup"), 
          type = c("single", "divorced", "single", "married", "single", "bachelorette")
)

library(tidyverse)

df |> 
          mutate(direction_lag = lag(direction)) |> 
          mutate(direction_lag = coalesce(direction_lag, direction)) |> 
          mutate(direction_new = case_when(
                    direction_lag == "down" & str_detect(direction, "up") ~ "down" , 
                    TRUE ~ direction),
                 type_new = case_when(
                           direction_lag == "down" & str_detect(direction, "up") ~ "CHANGED" , 
                              TRUE ~ type
          )) |> 
          select(-direction_lag)

Instead of ifelse I used case_when(), which I like very much.

The reasoning is that I create a lag that allows for a comparison with the row above, coalesce it to avoid the first row to have an NA.
Then I use case_when with the conditions you highlighted and eliminate the lagged column.

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