![]() I suggest predefining all possible levels and then using the replace() function. You could "solve" this by inverting the comparison: mutate(mycontinent = if_else(country != "Maldives", mycontinent, factor("Africa")))īut that's still not the shortest and most explanatory code for the task. The same thing happens with the Asia line, converting all not- "Asia" values to NA. All the other continents in mycontinent don't match that single level, so they become NA. Returns a factor vector based on factor("Africa"). Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more. ![]() Because if_else bases its return value on the true vector, if_else(country = "Maldives", factor("Africa"), mycontinent) W3Schools offers free online tutorials, references and exercises in all the major languages of the web. The forcats package can handle mismatched levels, but not inside other functions like if_else(). This tutorial will start with an overview of the comparison operators that will be used to build conditional statements. When combining factors, it's best to make sure they have the same levels beforehand. (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). If I now have to turn mycontinent back into a factor. #> "Europe" "North America" "Africa" "Asia" #> 2 Canada North America 1 North America Mutate(mycontinent = as.character(continent)) %>% #> Error in mutate_impl(.data, dots): Evaluation error: `false` must be type character, not integer. Mutate(mycontinent = if_else(country = "Seychelles", "Asia", mycontinent)) Mutate(mycontinent = if_else(country = "Maldives", "Africa", mycontinent)) %>% #> Levels: North America Europe Seven seas The if.else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. #> Europe North America Seven seas Seven seas ![]() Mutate(continent = fct_reorder(continent, myorder)) Mydata = data_frame(country = c("UK", "Canada", "Maldives", "Seychelles"),Ĭontinent = c("Europe", "North America", "Seven seas", "Seven seas"), He also has to remove the gap between 'else if'. ![]() My current work-around is changing it to a character but this doesn't retain the order of the factor levels: library(tidyverse) You should really drop that inline CSS as Paul stated in his comment while we are busy making it more readable. Is there a clever way to recode a factor based on another variable (so using if_else and adding new factor levels)? ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |