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!