Outra possível solução é usar todo() e ifelse(), por exemplo, se o valor na coluna x é menor do que quatro, realizar a mutação:
library(tidyverse)
tibble(x = c(1:2, 4:5), y = 1:4) %>%
mutate(across(everything(), ~ ifelse(x < 4, -.x, .x)))
#> # A tibble: 4 × 2
#> x y
#> <int> <int>
#> 1 -1 -1
#> 2 -2 -2
#> 3 4 3
#> 4 5 4
Criado em 2021-11-24 pelo reprex pacote (v2.0.1)
Você também pode aninhar ifelse juntos, por exemplo, se o valor na coluna x é menor do que 4, ou se um valor em qualquer coluna é igual a 3, mutar:
library(tidyverse)
tibble(x = c(1:2, 4:5), y = 1:4) %>%
mutate(across(everything(), ~ ifelse(x < 4, -.x,
ifelse(.x == 3, .x + 10, .x))))
#> # A tibble: 4 × 2
#> x y
#> <int> <dbl>
#> 1 -1 -1
#> 2 -2 -2
#> 3 4 13
#> 4 5 4
Criado em 2021-11-24 pelo reprex pacote (v2.0.1)
E, assim por diante:
library(tidyverse)
tibble(x = c(1:2, 4:5), y = 1:4) %>%
mutate(across(everything(), ~ ifelse(x < 4, -.x,
ifelse(.x == 3, .x + 10,
ifelse(.x >= 5, "outlier", .x)))))
#> # A tibble: 4 × 2
#> x y
#> <chr> <dbl>
#> 1 -1 -1
#> 2 -2 -2
#> 3 4 13
#> 4 outlier 4
Criado em 2021-11-24 pelo reprex pacote (v2.0.1)
--
Para fazer a mutação de forma mais eficiente, não use dplyr::mutação. Ifelse() função é vetorizados (mais detalhes: https://swcarpentry.github.io/r-novice-gapminder/09-vectorization/) e se você tiver um grande dataframe, ifelse sozinho, muito provavelmente será muito mais rápido do que tidyverse funções, e.g.
library(tidyverse)
df <- tibble(x = c(1:2, 4:5), y = 1:4)
df$y <- ifelse(df$x < 4, -df$y, df$y)
df
#> # A tibble: 4 × 2
#> x y
#> <int> <int>
#> 1 1 -1
#> 2 2 -2
#> 3 4 3
#> 4 5 4
Editar
Outra possível opção é substituir os valores por meio de atribuição: df$y[df$x < 4] <- -(df$y); df$x[df$x < 4] <- -(df$x)
(rápido, mas há limitações).
Aqui está uma rápida referência dos métodos sugeridos com 1 milhão de linhas:
library(tidyverse)
df <- tibble(x = sample(1:10, 1000000, replace = TRUE),
y = sample(1:10, 1000000, replace = TRUE))
mutate_func <- function(df){
df %>%
mutate(across(everything(), ~ ifelse(x < 4, -.x, .x)))
}
ifelse_func <- function(df){
df$y <- ifelse(df$x < 4, -df$y, df$y)
}
replacement_func <- function(df) {
df$y[df$x < 4] <- -(df$y)
df$x[df$x < 4] <- -(df$x)
}
mutate_when_func <- function(df) {
mutate_when <- function(.data, when, ...) {
dots <- enquos(...)
names <- names(dots)
mutate(.data, {
test <- {{ when }}
changed <- data.frame(!!!dots, stringsAsFactors = FALSE)
out <- across(all_of(names))
# assuming `changed` and `out` have the same data frame type
out[test, ] <- changed[test, ]
out
})
}
df %>%
mutate_when(x < 4, x = -x, y = -y)
}
library(microbenchmark)
result <- microbenchmark(mutate_func(df), ifelse_func(df),
mutate_when_func(df), replacement_func(df),
times = 10)
autoplot(result)