Problem: I wrote a gigantic piece of code with over 100 ifelse statements only to learn that there is a limit on the number of ifelse statements: exceeding 50 throws an error. Anyway, I know there is a more efficient way to do what I am trying to do.
Goal: Trying to write a function to recode many variants of strings (see below example) into clear categories (e.g. below). I use str_detect to give T/F and then change into the correct category based on response. How can I do this without over 100 ifelse statements (I have a lot more categories).
Example:
mydf <- data_frame(answer = sample(1:5, 10, replace = T),
location = c("at home", "home", "in a home",
"school", "my school", "School", "Work", "work",
"working", "work usually"))
loc_function <- function(x) {
home <- "home"
school <- "school"
work <- "work"
ifelse(str_detect(x, regex(home, ignore_case = T)), "At Home",
ifelse(str_detect(x, regex(school, ignore_case = T)), "At
School",
ifelse(str_detect(x, regex(work, ignore_case = T)), "At
Work", x)))
}
### Using function to clean up messy strings (and recode first column too) into clean categories
mycleandf <- mydf %>%
as_data_frame() %>%
mutate(answer = ifelse(answer >= 2, 1, 0)) %>%
mutate(location = loc_function(location)) %>%
select(answer, location)
Aucun commentaire:
Enregistrer un commentaire