I am trying to create an indictor variable, Z, in R, ie 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
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).
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)
}
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.