dplyr error with mutate() when attempting to change variable value based on if_else condition

Viewed 98

I am attempting to change the value of a variable using dplyr::mutate(). I want to change the value of the column 'certainty' from "unsure" to "likely" if the ID from a character vector is found in the ID column in the dataset. If it does not match, I would like to keep the original value. Here is a reprex with my current attempt:

library(dplyr)
library(magrittr)

data <- data.frame(
  ID = c("a100", "b100", "c100", "d100", "e100", "f100"),
  certainty = c("confirmed", "likely", "unsure", "likely", "unsure", "confirmed")
)

data %<>% as_tibble()

id_list <- c("c100", "e100")

data %<>%
  mutate(certainty = if_else(id_list %in% ID, "likely", certainty))

The output should look like this:

 ID    certainty
  <fct> <fct>    
1 a100  confirmed
2 b100  likely   
3 c100  likely   
4 d100  likely   
5 e100  likely   
6 f100  confirmed

Currently I get this error:

Error: `false` must be length 2 (length of `condition`) or one, not 6

How should I solve this?

1 Answers

The issue is with the order of arguments in %in%. It is returning the length of id_list which is 2 if we use id_list %in% ID. Instead it should be the other way i.e. ID %in% id_list e..g

1:3 %in% 1:2
#[1]  TRUE  TRUE FALSE

and

1:2 %in% 1:3
#[1] TRUE TRUE

Here, it would be

library(dplyr)
data %>% 
      mutate(certainty = ifelse(ID %in% id_list, "likely", as.character(certainty)))

# A tibble: 6 x 2
#  ID    certainty
#  <fct> <chr>    
#1 a100  confirmed
#2 b100  likely   
#3 c100  likely   
#4 d100  likely   
#5 e100  likely   
#6 f100  confirmed

NOTE: certainty is factor, so it needs to be converted to character or add likely as another level (if we want to stick to factor class)


It can be also be remained as factor

library(forcats)
data %>%
     mutate(certainty = fct_collapse(certainty,
              likely = as.character(certainty)[ID %in% id_list]))\
# A tibble: 6 x 2
#  ID    certainty
#  <fct> <fct>    
#1 a100  confirmed
#2 b100  likely   
#3 c100  likely   
#4 d100  likely   
#5 e100  likely   
#6 f100  confirmed
Related