首页 > 解决方案 > 使用 mutate_at 对多个变量进行 Boxcox 变换

问题描述

说,我想对以下数据(不是我正在使用的数据,只是为了解释我的问题)从 caret 包进行 boxcox 转换:

library(caret); library(tidyverse)
set.seed(001)
d <- tibble(a = rpois(20, 10), b = rnorm(20, 40, 10))
    head(d)
# A tibble: 6 x 2
      a     b
  <int> <dbl>
1     8  20.1
2    10  46.2
3     7  39.4
4    11  38.4
5    14  25.3
6    12  35.2

我可以通过运行来实现这一点

d1 <- BoxCoxTrans(d$a) %>% predict(d$a)

我可以重复相同的过程来转换 b。有没有办法可以使用 dplyr 同时对变量 a 和 b 进行 boxcox 转换?我尝试了以下但我无法弄清楚如何编写.funs

d %>% mutate_at(c("a", "b"), BoxCoxTrans %>% predict(d))

标签: rtransformationr-caretdplyr

解决方案


我从未使用过插入符号,但是这些解决方案是否有任何理由不适用于您的特定情况?(它们对我来说运行良好。)

library(tidyverse)
library(caret)
library(e1071)
set.seed(001)
d <- tibble(a = rpois(20, 10), b = rnorm(20, 40, 10))
head(d)

#On selected columns
d %>%
  mutate_at(vars(a,b), funs( BoxCoxTrans(.) %>% predict(.)))

#Or on all columns
d %>%
  mutate_all(funs( BoxCoxTrans(.) %>% predict(.)))

推荐阅读