[R] simplify if statement in R ?

Joshua Wiley jwiley.psych at gmail.com
Tue Jul 20 20:34:04 CEST 2010


Hi Jim,

Without a reproducible example I can't test my solution against yours,
but does this do what you are looking for?

#Some Sample data
x0.trial01 <- 1
x1.trial01 <- 2
npt01 <- 2

if(any(c(x0.trial01, x1.trial01) %in% c(0, npt01))) {
  x0.trial01.in <- x0.trial01 + 0.5
  x1.trial01.in <- x1.trial01 + 0.5
  npt01.in <- npt01 + 1.0
} else {
  x0.trial01.in <- x0.trial01
  x1.trial01.in <- x1.trial01
  npt01.in <- npt01
}

It simply tests whether any variables in the first vector (I combined
using c() ) match any variables in the second vector.

HTH,

Josh


On Tue, Jul 20, 2010 at 11:11 AM, Jim Maas <jimmaasuk at gmail.com> wrote:
> I found a form of the if statement that works but it is very long.  I'm
> attempting to check the value of of two different variables to see if they
> evaluate to either of two different values, which will result in a division
> by 0 in the final equation.  This first if statement works for me
> _______
>
>  if ((x0.trial01 == 0.0)||(x0.trial01 == npt01)||(x1.trial01 ==
> 0.0)||(x1.trial01 == npt01))
>        {
>            x0.trial01.in <- x0.trial01 + 0.5
>            x1.trial01.in <- x1.trial01 + 0.5
>            npt01.in <- npt01 + 1.0
>        }
>        else
>        {
>            x0.trial01.in <- x0.trial01
>            x1.trial01.in <- x1.trial01
>            npt01.in <- npt01
>        }
> __________
>
> I've tried
> if ( ( x0.trial01 || x1.trial01) == ( 0.0 || npt01) )
>    ......
>
>
> but it doesn't seem to work correctly.  Is there a simpler way to check two
> variables for two different valuables?
>
> Thanks
>
> J
>
> ----
> Jim Maas
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list