[R] nested if else statements

Joshua Wiley jwiley.psych at gmail.com
Sun Feb 5 23:55:22 CET 2012


Hi Philip,

You have gotten several good responses.  For a generalization of this,
I would suggest _not_ using nested if or ifelse statements.  They
quickly become difficult to read.

d <- c(1, 1, 2, 2, 2, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0)
require(car)
dnew <- recode(d, "2 = 0; 1 = 1; 0 = 2")

# > d
#  [1] 1 1 2 2 2 0 1 0 1 0 0 0 1 1 0 1 1 1 0 0
# > dnew
#  [1] 1 1 0 0 0 2 1 2 1 2 2 2 1 1 2 1 1 1 2 2

this allows for very readable code that works basically as one would
think...2 becomes 0, 1 becomes 1, 0 becomes 2.  You can also specify
an 'else' to catch everything not included in a specific statement.
To me, the readability and simplicity is worth a lot.  Under the hood,
it is a bit more complex, and perhaps not the most efficient so I
might rethink the readability if the run time takes too long because
you are working with huge amounts of data (20 million numbers only
takes 9 seconds to recode on my old laptop so definitely a lot more
than that).

Cheers,

Josh

On Sun, Feb 5, 2012 at 2:30 PM, Philip Robinson
<philip.c.robinson at gmail.com> wrote:
> I have a vector of 2,1,0 I want to change to 0,1,2 respectively (the data
> is allele dosages)
>
> I have tried multiple nested if/else statements and looked at the ?if help
> and cannot work out what is wrong, other people have posted code which is
> identical and they state works.
>
> Any help would be greatly appreciated.
>
>> A[1:20]
> [1] 1 1 0 0 1 0 1 0 1 0 0 0 1 1 0 1 1 1 0 0
>
>> B <- rep(NA,length(A))
>
>> for (i in 1:length(A)){ if(A[i]==2){B[i] <- 0} else
> +                         if(A[i]==0){B[i] <- 2} else
> +                         if(A[i]==1){B[i] <- 1}}
>
> Error in if (A[i] == 2) { : missing value where TRUE/FALSE needed
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list