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: