Mutating dataframe in R in only certain cases

Viewed 90

I have a dataframe in R with multiple columns that I want to manipulate depending on the value for a specific column. Here is a sample dataframe set up in the same way:

dat <- data.frame(A=c("L","Right","R","Left"), B=c(2,5,7,-8), C=c(-3,6,-4,9))
dat

If the value in column A is either "L" or "Left", I want to convert the other columns in that row to negative values unless the value is already negative. For example, in the first row, I would want the 2 to change to a negative 2, but keep the -3 the same. In the fourth row, I would want the -8 to stay the same, but want to change the 9 to a -9.

I previously used this code to convert to negative values, but this was when I was working with only positive values initially and did not want to leave some values unchanged.

library(dplyr)
dat <- dat %>% mutate(across(where(is.numeric), ~ if_else(grepl("^L", A), -1, 1) * .))

I am not sure how to change the above code to address this new issue, and I would greatly appreciate if someone could help answer this question. Thanks so much!

1 Answers

Take the absolute value and multiply it by -1 for L and sign(.) otherwise.

dat %>% 
  mutate(across(-1, ~ if_else(grepl("^L", A), -1, sign(.)) * abs(.)))

giving:

      A  B  C
1     L -2 -3
2 Right  5  6
3     R  7 -4
4  Left -8 -9

or

dat %>% 
  mutate(across(-1, ~ if_else(grepl("^L", A), -abs(.), .)))

Note that overwriting dat with the new value can make it harder to debug because then there can be confusion over which version of dat is the current one and if you try to rerun just the above line you will be starting with the second version rather than the first. Suggest using

dat2 <- dat %>% ...whatever...
Related