Jasper
Jasper

Reputation: 115

Recode variables with ifelse and is.na

I want to recode a variable based on another variable not being NA. In the example below, I want to subsitutename with new_name every time new_name is not NA. I guess it is very simple, but the solution I tried in the example did not work. Thank you for your help.

df <- structure(list(id = c(321, 452, 564, 678), name = c("Red", "White", "Black", "Blue"), 
                new_name = c("Pink", NA, NA, "Light blue")), row.names = c(NA, -4L), 
                class = c("tbl_df", "tbl", "data.frame"))

ifelse(is.na(df$new_name), 
       df$name == df$new_name, 
       df$name == df$name)

Upvotes: 1

Views: 744

Answers (1)

mhovd
mhovd

Reputation: 4067

You forgot to close your quotes in your example data. Here is a working example with case_when. There is no particular reason why I chose case_when over ifelse, but it is easier to build on if you have multiple conditions.

Also note than in your example code, if name_new is NA, name would be assigned name_new, opposite of what you described in your text if I interpreted your intention correctly.

library(dplyr)
#> Warning: package 'dplyr' was built under R version 4.0.3
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- structure(list(id = c(321, 452, 564, 678), name = c("Red", "White", "Black", "Blue"), 
                new_name = c("Pink", NA, NA, "Light blue")), row.names = c(NA, -4L), 
                class = c("tbl_df", "tbl", "data.frame"))


df %>% 
  mutate(name = case_when(
    !is.na(new_name) ~ new_name,
    !is.na(name) ~ name
  ))
#> # A tibble: 4 x 3
#>      id name       new_name  
#>   <dbl> <chr>      <chr>     
#> 1   321 Pink       Pink      
#> 2   452 White      <NA>      
#> 3   564 Black      <NA>      
#> 4   678 Light blue Light blue



# Alternative solution with `coalesce` (suggested by Martin Gal in comments)
df %>% 
  mutate(name = coalesce(name, new_name))
#> # A tibble: 4 x 3
#>      id name  new_name  
#>   <dbl> <chr> <chr>     
#> 1   321 Red   Pink      
#> 2   452 White <NA>      
#> 3   564 Black <NA>      
#> 4   678 Blue  Light blue

Created on 2021-08-24 by the reprex package (v0.3.0)

Upvotes: 3

Related Questions