case_when with mutate(across

The below line does not work, it does not convert the data per case_when, could you point out why?

change <- mtcars[,-1] %>% mutate(across(~ case_when(. <100 ~ 1,
                                                                                                                      . ==100 ~ 0,
                                                                                                                       . >100 ~ -1)))

This seems to work. You just have to specify which argument should get the formula.

library(dplyr,warn.conflicts = FALSE)
change <- mtcars[,-1] %>% mutate(across(.fns = ~ case_when(. <100 ~ 1,
                                                     . ==100 ~ 0,
                                                     . >100 ~ -1)))
head(change)
  cyl disp hp drat wt qsec vs am gear carb
1   1   -1 -1    1  1    1  1  1    1    1
2   1   -1 -1    1  1    1  1  1    1    1
3   1   -1  1    1  1    1  1  1    1    1
4   1   -1 -1    1  1    1  1  1    1    1
5   1   -1 -1    1  1    1  1  1    1    1
6   1   -1 -1    1  1    1  1  1    1    1

Many thanks !
I thought that you could use either .fns= or ~ to indicate a function.
I tried to use only across( ~ case_when... and it did not work, same thing with .fns= case_when... (which did run but without recoding).
Hope I slowly will get the difference :wink:

I would probably just use

change <- mtcars[,-1] %>%
mutate(across(.cols = everything(), ~ case_when(. <100 ~ 1,
. ==100 ~ 0,
. >100 ~ -1)))

to avoid having to remember the .fns= , but it is longer.

Ok, so placing only ~ before case_when is not enough for the across to tell it this is .fns argument, not .cols ? Unless of course .cols is specified first as in your example.

That is right; arguments can be passed by name, as I did with .fns, or by position but R will not use the class of a value to assign it to an argument.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.