4

I have a dataframe df. I would like to replace all zeros with ones and all ones with zeros in the dataframe. Or in general, if I have to find some value (like one) and replace the value with something else, what's the best approach?

  a b
1 1 0
2 0 1
3 1 0
4 0 0
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
yome
  • 2,853
  • 5
  • 20
  • 18
  • 4
    Just subtract 1 from the whole dataframe? `1 - df` (not sure how you do it with R :p) – cs95 Dec 29 '17 at 06:44
  • 2
    `abs(df - 1)` in R. @cᴏʟᴅsᴘᴇᴇᴅ – Ronak Shah Dec 29 '17 at 07:27
  • 3
    Possible duplicate of [Replace a value in a data frame based on a conditional (\`if\`) statement in R](https://stackoverflow.com/questions/5824173/replace-a-value-in-a-data-frame-based-on-a-conditional-if-statement-in-r) Or more generally [Dictionary style replace multiple items](https://stackoverflow.com/questions/7547597/dictionary-style-replace-multiple-items) – Ronak Shah Dec 29 '17 at 07:29

2 Answers2

6

A code golf would be to negate the dataset and use +

+(!df)
#  a b
#1 0 1
#2 1 0
#3 0 1
#4 1 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @ thanks, but in a general case, if I have to replace all zeros with a value (for example, 6) what to do in this case? – yome Dec 29 '17 at 06:48
  • @yome What about the `1s`? use `replace(df, !df, 6)` – akrun Dec 29 '17 at 06:48
  • 1s with another specific value lets say 5? – yome Dec 29 '17 at 06:52
  • @yome If you have many values to replace, you could use `case_when` or `if_else` one option in `dplyr` would be `df %>% mutate_all(funs(case_when(.==1~5L, .==0 ~ 6L, TRUE ~.)))` or in `base R`, `lapply(df, function(x) ifelse(x == 1, 5, ifelse(x == 0, 6, x)))` It depends on how many values you want to replace. A general approach would be key/value pair and then do the replacement for many values – akrun Dec 29 '17 at 06:55
  • can you help answer this? https://stackoverflow.com/questions/48019176/change-color-of-the-values-in-heatmap-in-highcharter-r-package – yome Dec 29 '17 at 08:30
2
mydata=data.frame(a=c(1,0,1,0),b=c(0,1,0,0));
psych::reverse.code(c(-1,-1),mydata)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174