Is there a clever way to recode a factor based on another variable (so using if_else
and adding new factor levels)?
My current work-around is changing it to a character but this doesn't retain the order of the factor levels:
library(tidyverse)
mydata = data_frame(country = c("UK", "Canada", "Maldives", "Seychelles"),
continent = c("Europe", "North America", "Seven seas", "Seven seas"),
myorder = c(2, 1, 3, 4)) %>%
mutate(continent = fct_reorder(continent, myorder))
mydata$continent
#> [1] Europe North America Seven seas Seven seas
#> Levels: North America Europe Seven seas
mydata %>%
mutate(mycontinent = continent) %>%
mutate(mycontinent = if_else(country == "Maldives", "Africa", mycontinent)) %>%
mutate(mycontinent = if_else(country == "Seychelles", "Asia", mycontinent))
#> Error in mutate_impl(.data, dots): Evaluation error: `false` must be type character, not integer.
newdata = mydata %>%
mutate(mycontinent = as.character(continent)) %>%
mutate(mycontinent = if_else(country == "Maldives", "Africa", mycontinent)) %>%
mutate(mycontinent = if_else(country == "Seychelles", "Asia", mycontinent))
newdata
#> # A tibble: 4 x 4
#> country continent myorder mycontinent
#> <chr> <fct> <dbl> <chr>
#> 1 UK Europe 2 Europe
#> 2 Canada North America 1 North America
#> 3 Maldives Seven seas 3 Africa
#> 4 Seychelles Seven seas 4 Asia
newdata$mycontinent
#> [1] "Europe" "North America" "Africa" "Asia"
If I now have to turn mycontinent
back into a factor.
(Which is this example is easy enough to do as I had the non-alphabetic order recorded in a variable, but sometime's I've used fct_relevel in a previous code chunk and would then have to copy/move that past this part now).
Created on 2018-09-10 by the reprex
package (v0.2.0).