【发布时间】:2020-10-26 22:22:07
【问题描述】:
我正在尝试在 mutate 命令中使用 switch 应用自定义函数,但我不断收到以下错误。
Error: Problem with `mutate()` input `new_col`.
x EXPR must be a length 1 vector
ℹ Input `new_col` is `example_func(col_name, trans)`.
我想要的最终结果是一个稍后将作为函数执行的字符串。
library(tidyverse)
## sample function
example_func <- function(pred, trans) {
switch(trans,
"None" = pred,
"Squared" = paste0(pred, "^2")
)
}
## test function (works)
example_func("b", "")
## data
dat <- data.frame(col_name = c("a", "b"),
trans = c("Squared", "None"))
## desired end result
dat[["new_col"]] <- c("a^2", "b")
dat
## trying to apply function to data (fails)
dat %>%
mutate(new_col = example_func(col_name, trans))
【问题讨论】:
-
switch()不是矢量化函数。如果要使用 dplyr 功能,最好使用case_when:example_func <- function(pred, trans) {case_when(trans=="None" ~ pred, trans=="Squared" ~ paste0(pred, "^2"))}
标签: r