I have a series of if
statements in a function. It looks like this:
my_func <- function(data, selection) {
if (selection == 'p+c') {
predictors = 'chicago'
preds <- data
}
else if (selection== 'p') {
predictors = 'new_york'
preds <- data %>% dplyr::select(-c(region, sale))
}
else if (selection == 'c') {
predictors = 'california'
preds <- data %>% dplyr::select(region, sale)
}
# then the function does something else with predictors and preds,
# and returns a dataframe
}
my_func(my_data, selection = 'p')
I keep getting the warning that the condition has length > 1 and only the first element will be used
. Weirdly, it doesn't actually break anything (it all works as expected), but I still would rather amend this problem.
I read that this is a problem with vectorization, but I don't know how to overcome this.
I already tried replacing the if/else with ifelse
(as suggested in other posts) but this did not work, maybe because I do more than one operation at each if
statement. I did this:
ifelse (selection == 'p+c') {
predictors = 'chicago'
preds <- data
}
ifelse (selection== 'p') {
predictors = 'new_york'
preds <- data %>% dplyr::select(-c(region, sale))
}
ifelse (selection == 'c') {
predictors = 'california'
preds <- data %>% dplyr::select(region, sale)
}