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
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
We can use
library(dplyr)
df1 %>%
mutate(value = case_when(indicator == 'X' ~ -1 * value, TRUE ~ value))
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