1

I am trying to change a value for a variable depending on other variables. So if value of one variable equals that of second variable then value of third variable should be multiplied by -1.

My code looks like this:

df <- df %>%
       mutate (C = case_when((A1) == (A2) & (R1) == (R2) ~ C,
                                (A1) == (R1) & (A2) == (R2) ~ (-1L)*C))

where A1, A2, R1, R2 are character variables and C is a numerical variable.

I get

error: case_when(...)`.
must be a double vector, not a logical vector.

If I change (-1L) to (-1) then it gives me NA for C

TIA!!

deschen
  • 10,012
  • 3
  • 27
  • 50
craby111
  • 15
  • 3
  • Welcome on Stackoverflow. To help you, plese follow these instructions: https://stackoverflow.com/help/minimal-reproducible-example – deschen Feb 09 '22 at 22:51

1 Answers1

0

Maybe the following will solve the problem.
Instead of checking the condition where there are no changes, leave only the changes condition and all others in the TRUE clause.

df <- df %>%
  mutate(
    C = case_when(
      (A1 == R1) & (A2 == R2) ~ -1L*C,
      TRUE ~ C
  ))
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66