How to conditionally replace observations with NA?

How would I go about conditionally replacing an observation with NA?

REGION MANAGER STATUS Address
Igor Closed Smith St
Helena Open Peters St
Igor Closed Elver St
Helena Open Brownburg St
Igor Open Edel St

If the status is "Closed" I want to list the address as NA, conditionally. Would I use case_when? Or if_else?

I tried:

data <- data %>% if_else(STATUS == "Closed", Address == NA, Address == Address`)

but get this error:Error: condition must be a logical vector, not a tbl_df/tbl/data.frame object.

This is my goal:

REGION MANAGER STATUS Address
Igor Closed NA
Helena Open Peters St
Igor Closed NA
Helena Open Brownburg St
Igor Open Edel St

Thank you

You have tried writing:

I'll start by just explaining why this didn't work!

  • A pipe puts the left hand side into the first argument of the function on the right hand side. if_else() doesn't take a dataframe as an argument.
  • Address == NA literally means "is the adress equal to NA", which is, a), not what you want and, b), never appropriate anyway as to detect NA values you'd use is.na().

The correct syntax looks like this:

library(tidyverse)

df = read_table("REGION MANAGER STATUS  Address
           Igor Closed  Smith St
           Helena   Open    Peters St
           Igor Closed  Elver St
           Helena   Open    Brownburg St
           Igor Open    Edel St")

df %>%
  mutate(Address = if_else(MANAGER == "Closed", NA_character_, Address))
#> # A tibble: 5 x 4
#>   REGION MANAGER STATUS    Address
#>   <chr>  <chr>   <chr>     <chr>  
#> 1 Igor   Closed  Smith     <NA>   
#> 2 Helena Open    Peters    St     
#> 3 Igor   Closed  Elver     <NA>   
#> 4 Helena Open    Brownburg St     
#> 5 Igor   Open    Edel      St
  • We are changing columns, so we use mutate().
  • The "Address" column is equal to the if_else() call.
  • Our condition is "is the MANAGER column equal to 'closed'?"
  • If TRUE, replace with NA_character_ (as it is a character column)
  • If FALSE, replace with itself (i.e., don't change it)
1 Like

Thank you for such thorough explanation of this!

1 Like

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.