Here are some things which I first used when getting to know R (and Matlab).
R function Matlab function What it does... x<<-global x defines x so that it can be called globally x%%y mod(x,y) x mod y abs(x) abs(x) gives the absolute value of x all(x==a) all(x=a) gives a boolean value if all elements of x have the value a any(x==a) any(x=a) gives a boolean value if the value a is found apply(x,a,fun) ? applies the function fun to x a-wise [eg a=2 is columnwise. fun can be eg all, any, min, max, sum... diag(n) eye(n) gives an nxn identity matrix dim(x) size(x) gives a (row) vector of the dimensions of x for(i in a:b){
statements
}for i=a:b
statements
endfor loop to repeat statements over index i if( condition(s)){
statements
}if condition(s)
statements
enda conditional set of statements intersect(x,y)
is.element
setdiff(x,y)
union(x,y)same set operations length(x) length(x) returns the length of a vector x matrix(0,a,b) zeros(a,b) creates a matrix of zeroes, of dimension (a,b) matrix(1,a,b) ones(a,b) creates a matrix of ones, of dimension (a,b) matrix(x,dim, byrow=F) reshape(x,size) reshapes x to have dimension dim (or size) by column nrow(x),ncol(x) size(x,a) [eg a=1] number of rows resp. columns of x order(x) [a b]=min(x) gives the indices of elements of x in ascending numerical size prod(x) prod(x) multiplies all elements of x a<-readline("text")? prints text and user input saved into variable solve(a,b) a/b gives the solution to Ax=b solve(b,a) a\b gives the solution to xA=b sort(x) sort(x) sorts the elements of x sqrt(x) sqrt(x) square root of x sum(x) sum(x) sums the elements of x (whether a vector or matrix) which(x==a) find(x=a) gives the indices into x with value a while( condition(s)){
statements
}while condition(s)
statements
endrepeat a set of statements until a condition is met unique(x) unique(x) returns x without duplicate entries
One of the main problematic things that i find with R is dimensions, or rather lack of it. I find it helpful to make sure vectors have dimension (i.e. a row or column matrix) when they are inputted into a function. This goes also for when you select a subset of a vector or matrix, since this drops the dimension attributes. Two functions which you may find useful with this are as.row and as.column. These are my modified and translated versions of some matlab code, originally by Maarten Jansen.[top]