1

I am trying to create an indictor variable, Z, in R, i.e If I have some event A, I want Z to give a result of 1 if A is true and 0 if A is false. I have tried this:

Z=0
if(A==(d>=5 && d<=10))
  {
    Z=1
  }
  else
  {
    Z=0
  }

But this doesn't work. I was also thinking i could try to write a separate function called indicator:

indicator = function()

Any suggestions would be really helpful, thank you

user3438924
  • 23
  • 1
  • 1
  • 3

4 Answers4

3

You could easily write something like this

indicator<-function(condition) ifelse(condition,1,0)

ifelse can be used on vectors, but it works perfectly fine on single logical values (TRUE or FALSE).

Max Candocia
  • 4,294
  • 35
  • 58
2

Booleans FALSE / TRUE can be coerced to be 0 or 1 and then be multiplied:

Indicator<-function(x, min=0, max=Inf)
    { 
        as.numeric(x >= min) * as.numeric(x <= max)
    }
falsarella
  • 12,217
  • 9
  • 69
  • 115
0

You can use

a <- data.frame(a = -5:5, b = 1:11) indicator <- function(data) I(data > 0) + 1 - 1 indicator(a)

a can be vector, data frame...

And you can chance the logical in I function with your interest.

-1

There is no need to define A, just test the condition. Also, remember that && and & have different uses in R (see R - boolean operators && and || for more details), so maybe that is part of your problem.

if (d>=5 & d<=10)
   {
   Z <- 1
   }
  else
   {
   Z <- 0
   }

Or, as suggested in the other answer use ifelse:

z <- ifelse((d>=5 & d<=10), 1, 0)
Community
  • 1
  • 1
nico
  • 50,859
  • 17
  • 87
  • 112