41

I'm currently trying to update values from a data.frame using dplyr but I don't know if it is possible to replace a subset of values?

net4 <- read.table(text="
temps2 NNET NET ave
1     18    2   4  36
2     18    2   4  36
3     22    2   4  44
4     18    2   4  36
5     22    2   4  44
6     27    3   4  36", header=TRUE)

# I would like to do the same command line as below:
subs <- (net4$ave < 10 & net4$ave!=net4$temps2)
net4$ave[subs] <- with(net4[subs,], temps2/NNET*NET)

Thanks

Mark
  • 7,785
  • 2
  • 14
  • 34
droopy
  • 2,788
  • 1
  • 14
  • 12

1 Answers1

51

Use mutate and ifelse

library(dplyr)

mutate(net4,
  ave = ifelse(ave < 10 & ave != temp2, temps2 / NNET * NET, ave)
)
Mark
  • 7,785
  • 2
  • 14
  • 34
hadley
  • 102,019
  • 32
  • 183
  • 245