R IF Else Statement


Syntax: if (condition) {...} else {...}. && and || can be used in the condition. If else statement can be nested.


Let's create a vector containing number 1-10:

>samples <- c(rep(1:10))
>samples

[1] 1 2 3 4 5 6 7 8 9 10


Print out those sample numbers that are even using if else statement:

>for (thissample in samples)
+{
+ if (thissample %% 2 != 0) next
+ else print(thissample)
+}

[1] 2
[1] 4
[1] 6
[1] 8
[1] 10


The ifelse function is a vectorized version of if else statement. It's syntax is ifelse(condition,v1,v2). if contidion is true, return v1, otherwise v2.

If we want all samples with number >6 be number 2, and those not be number 1, just:

>ret<-ifelse(samples>6,2,1)
>ret

[1] 1 1 1 1 1 1 2 2 2 2


endmemo.com © 2024  | Terms of Use | Privacy | Home