According to the current documentation, you should be using across
-based syntax to perform operations on a desired subset of columns. You can use everything
to select all columns or use any other available qualifier. You should only use group_by
verb if your desire is to perform operation on groups. group_by
is not right choice for selecting variables.
mtcars %>%
as_tibble() %>%
mutate(across(where(is.numeric), ~ . - mean(.)))
As for the actual standardisation or any other operation you want to apply to the subset of columns you can use:
.fns Functions to apply to each of the selected columns. Possible
values are:
NULL
, to returns the columns untransformed.
- A function, e.g.
mean
.
- A purrr-style lambda, e.g.
~ mean(.x, na.rm = TRUE)
- A list of functions/lambdas, e.g.
list(mean = mean, n_miss = ~ sum(is.na(.x))
So for scale
you can do:
mtcars %>%
as_tibble() %>%
mutate(across(where(is.numeric), scale))
or with additional arguments
mtcars %>%
as_tibble() %>%
mutate(across(where(is.numeric), scale, center = FALSE))
Side notes
As you can see from ?scale
documentation, the function returns matrix. In case of the examples above, you will get matrix with one column if this bothers you, you can do:
mtcars %>%
as_tibble() %>%
mutate(across(where(is.numeric), ~ scale(.)[,1]))
Comparison
>> mtcars %>%
... as_tibble() %>%
... mutate(across(where(is.numeric), ~ scale(.)[,1])) %>%
... glimpse()
Rows: 32
Columns: 11
$ mpg <dbl> 0.15088482, 0.15088482, 0.44954345, 0.21725341, -0.23073453, -0.33028740, -0.96078…
$ cyl <dbl> -0.1049878, -0.1049878, -1.2248578, -0.1049878, 1.0148821, -0.1049878, 1.0148821, …
$ disp <dbl> -0.57061982, -0.57061982, -0.99018209, 0.22009369, 1.04308123, -0.04616698, 1.0430…
$ hp <dbl> -0.53509284, -0.53509284, -0.78304046, -0.53509284, 0.41294217,
...
>>
>>
>> mtcars %>%
... as_tibble() %>%
... mutate(across(where(is.numeric), scale)) %>%
... glimpse()
Rows: 32
Columns: 11
$ mpg <dbl[,1]> <matrix[32 x 1]>
$ cyl <dbl[,1]> <matrix[32 x 1]>
$ disp <dbl[,1]> <matrix[32 x 1]>
$ hp <dbl[,1]> <matrix[32 x 1]>
...