2

I have a simple dataframe and I wanted to transform the column X using dplyr, such that a constant value 20 is subtracted from all elements in X, if and only if I==1.

library(dplyr)
myData<-data.frame(
  I=as.factor(c(1,2,1)),
  X=c(4,2,3)
)

How can achieve this behavior. My first attempt was to use:

result<-myData%>% filter(I==1) %>% mutate(X=X-20)

But now I don't know how to merge result back to myData? I also tried mutate_if, but I'm unsure, how to use it.

A basic R alternative solution might be:

myData$X[myData$I==1]=myData$X[myData$I==1]-20

But as I said I'm looking for a dplyr solution:

Aleph0
  • 5,816
  • 4
  • 29
  • 80
  • Relevant post where OP wants to [avoid using ifelse](https://stackoverflow.com/questions/34096162). Another relevant post, [using case_when](https://stackoverflow.com/questions/38649533) – zx8754 Jan 25 '18 at 11:23

1 Answers1

4

Using if_else:

myData %>% 
  mutate(X = X - if_else(I == "1", 20, 0))

# Or
myData %>% 
  mutate(X = if_else(I == "1", X - 20, X))

#   I   X
# 1 1 -16
# 2 2   2
# 3 1 -17
zx8754
  • 52,746
  • 12
  • 114
  • 209