MODULE 4.1 Operators and Functions in R

baseR-V2016.2 - Data Management and Manipulation using R

Tested on R versions 3.0.X through 3.3.1
Last update: 15 August 2016


Objectives:

  • What are some commonly used functions in R?

  • What operations are performed by:

    • Basic R functions?

    • Operators?

    • Mathematical functions?

    • Vector functions?

    • Functions for character strings?

This Module shows examples of many of the more commonly used operators and functions. It is not an exhaustive list.



Let’s begin with …

Some Basic Functions Available in R


Some of the most commonly used functions for dealing with data are:

Function Purpose Function Purpose
nrow() No. of rows in object str() structure of object
ncol() No. columns in object class() var characteristics
length() length of vector cbind() bind objects by columns
names() var names in object rbind() bind objects by rows
ls() list workspace objects; also rm() & remove named objects;
ists R Values of functions rm(list=ls()) remove all objects

WARNING!!
rm(list=ls()) removes everything in your current workspace. Objects are permanently removed and no recovery is possible unless you previously saved your objects as a .RData file.


Common Mathematical Operators


Commonly used mathematocal operators for dealing with data are:

Operator Function Operator Function
+ addition < and <= less than (and equal)
- subtraction > and >= greater than (and equal)
/ division != not equal to
* multiplication == equal to
: sequence of values & and
^ or ** exponentiation “|” or

Common Mathematical Functions


Commonly used mathematical functions for dealing with data are:

Operator Function Operator Function
log(x) & log10(x) log^e & log^10 cos(x) & acos(x) cos & arccosine of x
sqrt(x) square root of x tan(x) & atan(x) tangent/arctangent of x
abs(x) absolute value of x floor(x) integer < x
round(x, digits = n) round x to digits=n ceiling(x) integer > x
exp(x) e^x sin(x) & asin(x) sin & arcsine of x

See the CRAN for a complete list.


Basic Vector Functions


Basic Vector functions for dealing with data are:

Function Operation Function Operation
min(x) & max(x) min / max of x range(x) value range in x
sum(x) sum of all x colSums(x) sum of columns in x
mean(x) & median(x) mean and median of x colMeans(x) mean of columns in x
sd(x) standard deviation of x rowSums(x) sum of rows in x
var(x) sample variance of x rowMeans(x) mean of rows in x

Functions for Character Strings


Basic functions for dealing with character strings are:

Function Purpose
substr(x, start, stop) extract from string x characters at location start to location stop
paste(x, y, sep = “”) paste characters in objects x and y together, with no separation
tolower(x) convert characters in x to lower case
toupper(x) convert characters in x to lower case
nchar(x) determine the number of characters in string x, including spaces

END MODULE 4.1


Printable Version