-2

I have a data frame that contains an indicator and a value, whenever that indicator = "X", i want to negatate the corpsonding value.

I can do this easily using the which, finding the indecies and negating, but would like to use dplyr

AJ Jebelli
  • 101
  • 6
  • 2
    Please take a look at how to make a [great reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Regarding your question... try something like `df %>% mutate(value=ifelse(indicator=='X', -value, value))`. – Martin Gal Jul 15 '21 at 21:20

2 Answers2

0

We can use

library(dplyr)
df1 %>%
     mutate(value = case_when(indicator == 'X' ~ -1 * value, TRUE ~ value))
akrun
  • 874,273
  • 37
  • 540
  • 662
-1

Considering you have a dataframe as this -

df <- data.frame(indicator = c('X', 'Y', 'X', 'X', 'Y', 'Y'), value = 1:6)
df

#  indicator value
#1         X     1
#2         Y     2
#3         X     3
#4         X     4
#5         Y     5
#6         Y     6

You can use -

df$value[df$indicator == 'X'] <- df$value[df$indicator == 'X'] * -1

df
#  indicator value
#1         X    -1
#2         Y     2
#3         X    -3
#4         X    -4
#5         Y     5
#6         Y     6
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213