'How to Use $ and | Logical operators together In R

=if(OR([a]="1",AND([b]<=50,[b]>0)),1,0) - Excel Formula

How Can i Write this as an R code:

below is the code which i tried

i = 1
for (i in 1: length(a))
{
  if((dataframe$a[i] == 1) || ((dataframe$b[i] <= 50) && (dataframe$b[i}> 0)))
  {dataframe$c[i] <- as.numeric(1);}
  else
  {dataframe$c[i] <- as.numeric(0);}
}
}

I get the following Errors:

Error: unexpected numeric constant in: Error: unexpected 'else' in " else Error: unexpected numeric constant in " Error: unexpected '}' in "}"

r


Solution 1:[1]

You can try

within(dat, c <- ((0 < b  & b <= 50 ) | a == 1) + 0 )

data

set.seed(25)
dat <- data.frame(a=sample(1:5, 100, replace=TRUE), 
       b= sample(-10:100, 100, replace=TRUE))

Solution 2:[2]

There was a "typo" in dataframe$b[i} and one extra }.

So, sample data from @akrun:

set.seed(25)
dat <- data.frame(a=sample(1:5, 100, replace=TRUE), 
       b= sample(-10:100, 100, replace=TRUE))

Code:

i = 1
for (i in 1: length(dat$a)){
  if((dat$a[i] == 1) || ((dat$b[i] <= 50) && (dat$b[i]> 0))){
    dat$c[i] <- as.numeric(1)
  } else {
    dat$c[i] <- as.numeric(0)
    }
} 

Also works with single operator:

i = 1
for (i in 1: length(dat$a)){
  if((dat$a[i] == 1) | ((dat$b[i] <= 50) & (dat$b[i]> 0))){
    dat$c[i] <- as.numeric(1)
  } else {
    dat$c[i] <- as.numeric(0)
    }
}

See the diference between single and double operators here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akrun
Solution 2 Yuri Gelsleichter