-4

I need to set a function that help me in restore the Yes/No variable in 0/1 one.

A function should be

x<-function(DataFrame,VariableName,Yes,No){
   .....
  }

I set up this code but run only out the function because R do not read the variable setted in () after the dollar sign.

dummy<-function(DB,varr){
        BD$varr <- as.character(DB$varr)
        DB[BD$varr=="Yes"]<-"1"
        DB[BD$varr=="No"]<-"0"
}
  • 6
    Possible duplicate of [How do I change a value coded as "Yes" to a value of 1 in R?](http://stackoverflow.com/questions/12033960/how-do-i-change-a-value-coded-as-yes-to-a-value-of-1-in-r) . Replace 2 with 0 everywhere in any of the answer. Or [r program changing yes/no variable to 1/0](http://stackoverflow.com/questions/38944567/r-program-changing-yes-no-variable-to-1-0-variable-medal-is-not-a-factor) – Ronak Shah Jan 03 '17 at 10:18
  • Use `[` instead of `$`. – Roland Jan 03 '17 at 10:29
  • 2
    `x<-function(DataFrame,VariableName,Yes) { as.integer(DataFrame[VariableName]==Yes) }` should do for your overall question. – Tensibai Jan 03 '17 at 10:36
  • For its use: `DB$Varr <- x(DB,"Varr","Yes")`. As an advice:don't try to update an external object in a function, even if you exactly know the caveats behind this idea, it's usually brittle and a nightmare to maintain. – Tensibai Jan 03 '17 at 10:44

1 Answers1

1

We can use as.integer to coerce the logical vector to binary

as.integer(BD$varr=="Yes")
akrun
  • 874,273
  • 37
  • 540
  • 662