R has the standard control structures you would expect. expr can be multiple (compound) statements by enclosing them in braces { }. It is more efficient to use built-in functions rather than control structures whenever possible.
# transpose of a matrix# a poor alternative to built-in t() function
mytrans <-function(x){if(!is.matrix(x)){
warning("argument is not a matrix: returning NA")
return(NA_real_)}
y <- matrix(1, nrow=ncol(x), ncol=nrow(x))for(i in1:nrow(x)){for(j in1:ncol(x)){
y[j,i]<- x[i,j]}}
return(y)}# try it
z <- matrix(1:10, nrow=5, ncol=2)
tz <- mytrans(z)ขับเคลื่อนโดย
R has the standard control structures you would expect. expr can be multiple (compound) statements by enclosing them in braces { }. It is more efficient to use built-in functions rather than control structures whenever possible.
if-else
for
while
switch
ifelse
Example
Going Further
To practice working with control structures in R, try the chapter on conditionals and control flow of this interactive R course.