library(tidyverse)
library(forcats)
I have two simple dataframes (code at bottom) and I want to create a new recoded variable by collapsing the "Animal" column. I usually do this with forcats::fct_collapse. However, I want to make a function to apply fct_collapse to many different dataframes that have the same variables, except that some might be missing one or two of the factor levels. For example, in this case, Df2 is missing "Rhino".
Is there a way I can change the code (using tiyverse) so that factor categories that are missing will be returned as NA? In this example I know it's "Rhino", but in my real data there may be other missing levels. I'm open to other options besides forcats::fct_collapse, but I would like to stay within the realm of tidyverse.
REC <- function(Df, Data){
Df %>%
mutate(NEW = fct_collapse(Data, One = c("Cat","Dog","Snake"),
Two = c("Elephant","Bird","Rhino")))
}
REC(Df1,Animal) - this works
REC(DF2,Animal) - this doesn't, it throws an error because of "Rhino"
Sample Data:
Animal <- c("Cat","Dog","Snake","Elephant","Bird","Rhino")
Code <- c(101,222,434,545,444,665)
Animal2 <- c("Cat","Dog","Snake","Elephant","Bird")
Code2 <- c(101,222,434,545,444)
Df1 <- data_frame(Code, Animal)
Df2 <- data_frame(Code2, Animal2) %> %rename(Animal = Animal2)