-4
x1 <- c("agree","disagree","agree","agree","agree","disagree","disagree")

How to replace agree=1 and disagree=0 for large atomic vectors or specific row/columns in a data frame?

m0nhawk
  • 22,980
  • 9
  • 45
  • 73
  • 2
    Some duplicates to get you started: [duplicate 1](http://stackoverflow.com/q/3905038/903061), [duplicate 2](http://stackoverflow.com/q/29562455/903061), [duplicate 3](http://stackoverflow.com/q/17717864/903061), also see `?replace` or `?factor`. – Gregor Thomas Jan 07 '16 at 17:08

2 Answers2

4

You can do something like this

ifelse(x1 == 'agree', 1, 0)

More conditions can be added as necessary.

akrun
  • 874,273
  • 37
  • 540
  • 662
Gopala
  • 10,363
  • 7
  • 45
  • 77
  • 1
    While this works (and it’s my preferred option in this simple case), adding more options is actually quite a hassle; this solution thus doesn’t scale very well beyond two values. `switch` alleviates this — but only somewhat, since the function is restricted to very specific input. The more general solution in R is to use factors. – Konrad Rudolph Jan 07 '16 at 17:09
  • Yes, as.factor() is correct way to handle categorical data. But the question was very specific. – Gopala Jan 07 '16 at 17:12
4

We can use + to convert the logical to binary

+(x1=="agree")

Or using as.integer (as per comments)

as.integer(x1 == "agree")

This method is much faster than the ifelse.

 set.seed(24)
 x2 <- sample(c("agree", "disagree"), 1e7, replace=TRUE)
 system.time(+(x2=="agree"))
 #  user  system elapsed 
 #  0.32    0.06    0.40 
 system.time(ifelse(x2=="agree", 1,0))
 #  user  system elapsed 
 #   3.20    0.91    4.10 
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I need to get used to starting a statement with a +. :) – Gopala Jan 07 '16 at 17:13
  • 4
    @user3949008 - No, you really shouldn't. `as.integer()` is more appropriate. – Rich Scriven Jan 07 '16 at 17:14
  • 6
    “no need”, sure. But no need for your solution either, which is after all much less explicit and thus less readable, and relies on a purely incidental type conversion to achieve the desired effect. In other words, too “clever”. I **really** discourage this solution. Know about it if you wish. Just please never use it. – Konrad Rudolph Jan 07 '16 at 17:16