I have two data frames: main_df is the master table. addl_df is a smaller table.
GOAL: to convert all character variables in addl_df as factors with the same levels as the character variables with the same names in main_df.
main_df <- data.frame(id=c(1, 2, 3, 4, 5), age=c(10, 20, 30, 40, 45), gender=c("F","F","M","M","F"), city=c("A","B","C","D","D"))
addl_df <- data.frame(id=c(7,8), age=c( 40, 45), gender=c("F","F"), city=c("C","D"))
Using the code below, city will be a factor variable with 2 levels ("C" and "D). What I want is a factor w/ 4 levels "A","B","C","D" with "C" has value of 3 (same as how it's defined in main_df).
Is it possible to do this in an automated way (instead of manually defining the variable one-by-one? Thank you!
main_df[sapply(main_df, is.character)] <- lapply(main_df[sapply(main_df, is.character)], as.factor)
addl_df[sapply(addl_df, is.character)] <- lapply(addl_df[sapply(addl_df, is.character)], as.factor)
