【问题标题】:Using switch inside a mutate command [duplicate]在变异命令中使用 switch [重复]
【发布时间】: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_whenexample_func &lt;- function(pred, trans) {case_when(trans=="None" ~ pred, trans=="Squared" ~ paste0(pred, "^2"))}

标签: r


【解决方案1】:

我们可以使用rowwise,因为函数是switch,而switchvectorlength 1 用于'EXPR'

根据?switch

EXPR - 计算结果为数字或字符串的表达式。

所以,它不是数字或字符串

library(dplyr)
dat %>% 
   rowwise %>% 
   mutate(new_col = example_func(col_name, trans)) %>%
   ungroup

【讨论】:

    猜你喜欢
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多