R Command Cheat Sheet Page 3

ADVERTISEMENT

unif
Uniform
min, max
0,1
## calculate 5! using a for loop
For Loops
for(i in <vector>){ do stuff }
ans <- 1
for(i in 1:5){ ans <- ans*i }
ans
120
## Threshold ans at 100
if/else
if(<logical value>) { do stuff }
if(ans > 100){ ans2 <- 100}
else { do other stuff }
else{ ans2 <- ans}
ans2
100
Functions
func.name <- function(arg1, arg2, ...){ do stuff; return(ans)}
## Function to do factorial
my.factorial <- function(x){
if(!is.integer(x))
stop(“x must be an integer”)
ans <- 1
for(i in 1:x){ ans <- ans*i }
return(ans)
}
my.factorial(5)
120
Useful links:

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 3