【发布时间】:2023-03-10 13:04:01
【问题描述】:
我在一个函数中有一系列if 语句。它看起来像这样:
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')
我不断收到the condition has length > 1 and only the first element will be used 的警告。奇怪的是,它实际上并没有破坏任何东西(一切都按预期工作),但我仍然宁愿修改这个问题。
我读到这是矢量化的问题,但我不知道如何解决这个问题。
我已经尝试将 if/else 替换为 ifelse(如其他帖子中所建议的那样),但这不起作用,可能是因为我在每个 if 语句中执行了多个操作。我这样做了:
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)
}
【问题讨论】:
-
“我已经尝试用 ifelse 替换 if/else(如其他帖子中所建议的那样),但这不起作用”——显示您尝试过的内容。对
ifelse进行嵌套调用是没有问题的。 -
您根本没有将
ifelse用作函数。如果您熟悉 Excel,ifelse的作用类似于 Excel 的IF函数。 -
这意味着
selection中包含多个值,例如c('p+c', 'p')。在这种情况下会输出什么? -
selection包含什么内容? -
您的代码对我来说仍然无法重现或清晰。所以
selection可以有 3 个值,但在这种情况下预期的输出是什么?考虑添加一个示例虚拟数据帧并向我们展示它的预期输出。阅读how to give a reproducible example
标签: r