For my data frame, in the column Unit, if "mg" is found, it is replaced with "g" and then the corresponding value in the column "Mass" is divided by 1000. I used mutate twice to achieve this. Is there any ways to combine the two mutate into one?
df %>% mutate(unit = case_when(unit == "mg" ~ "g"))
df %>% mutate(mass = case_when(unit == "mg" ~ mass / 1000))
CodePudding user response:
Create the logical condition as a column and reuse. As the replacement values are different, it is better to have it separately. Also, case_when
by default changes the rest of the elements to NA
. If the OP meant to keep the rest of the values from the original column, specify the TRUE ~
condition
library(dplyr)
df <- df %>%
mutate(i1 = unit == 'mg',
unit = case_when(i1 ~ 'g', TRUE ~ unit),
mass = case_when(i1~ mass/1000, TRUE ~ mass), i1 = NULL)
CodePudding user response:
We can include several transformations (in this case the two transformations) inside the same mutate
call, with a reversed order. If your case_when statement is that simple, ifelse
is enought:
library(dplyr)
df %>% mutate(mass = ifelse(unit == 'mg', mass / 1000, mass),
unit = ifelse(unit == 'mg', 'g', unit))