When combining factors, it's best to make sure they have the same levels beforehand. The forcats package can handle mismatched levels, but not inside other functions like if_else(). Because if_else bases its return value on the true vector,
if_else(country == "Maldives", factor("Africa"), mycontinent)
returns a factor vector based on factor("Africa"). This means its only level is "Africa". All the other continents in mycontinent don't match that single level, so they become NA. The same thing happens with the Asia line, converting all not-"Asia" values to NA. You could "solve" this by inverting the comparison:
mutate(mycontinent = if_else(country != "Maldives", mycontinent, factor("Africa")))
But that's still not the shortest and most explanatory code for the task. I suggest predefining all possible levels and then using the replace() function.
all_continents <- c(
"Europe", "North America", "South America", "Africa", "Australia", "Asia",
"Antarctica", "Seven seas"
)
data_frame(country = c("UK", "Canada", "Maldives", "Seychelles"),
continent = c("Europe", "North America", "Seven seas", "Seven seas"),
myorder = c(2, 1, 3, 4)) %>%
mutate(mycontinent = factor(continent, all_continents)) %>%
mutate(mycontinent = fct_reorder(mycontinent, myorder)) %>%
mutate(mycontinent = replace(mycontinent, country == "Maldives", "Africa")) %>%
mutate(mycontinent = replace(mycontinent, country == "Seychelles", "Asia"))
# # A tibble: 4 x 3
# country continent myorder
# <chr> <fct> <dbl>
# 1 UK Europe 2
# 2 Canada North America 1
# 3 Maldives Africa 3
# 4 Seychelles Asia 4