Reputation: 335
I want to multiply values with two different factors conditionally, let's say times 10, if values are <7, and times 5, if values are >= 7.
I tried to use case_when inside mutate and across, but it didn't work.
library(tidyverse)
df <- as_tibble(iris)
df_new <- df %>%
mutate(across(1:4, ~ case_when(. < 7 ~ * 10, . >= 7 ~ * 5)))
Is this even possible with case_when()?
Upvotes: 0
Views: 689
Reputation: 4232
library(dplyr)
iris %>%
mutate(across(1:4, ~ case_when(.x < 7 ~ .x * 10,
.x >= 7 ~ .x * 5))) %>%
head(10)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1 51 35 14 2 setosa
#> 2 49 30 14 2 setosa
#> 3 47 32 13 2 setosa
#> 4 46 31 15 2 setosa
#> 5 50 36 14 2 setosa
#> 6 54 39 17 4 setosa
#> 7 46 34 14 3 setosa
#> 8 50 34 15 2 setosa
#> 9 44 29 14 2 setosa
#> 10 49 31 15 1 setosa
Upvotes: 1