Operators

Assignment operators

As you noted in my previous page, I used the equal sign (=) to assign a value to a letter variable; that is called an assignment operator. Another more broadly recommended assignment operator is >-, which is used like this:

a<-10 # in this case I used <- as the assigment operators

Note that in the code above I use >- instead of =

I can verify this, by typing a in the R console and then hitting enter.

a
## [1] 10

Arithmetic operators

R is preloaded with a lot of built-in mathematical operators. Here are some basic ones:

Function Description
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponent
log(x) Natural log
log10(x) Common log
abs(x) Absolute value
sqrt(x) Square root
ceiling(x) Round to largest integer
floor(x) Round to smallest integer
round(x, digits = 0) Round number to given number of digits
rep(x, times = 1) Repeat a number a given number of times
seq(from, to, by= ) Create a sequence of numbers
sample(x,n,replace=T) Select n random numbers from vector x

Lets say I have a variable a=145.677, but I one to stimate the largest integer of that number, then

a=145.677
b=ceiling(a)
b
## [1] 146

Give a try to some of these operators, yourself.

Any time you need an operator, but you do not know what is it in R, simply ask your friend Google. Say you want to calculate the cosine of a number?. Simply search in Google “How to calculate a cosine in R”.

Character operators

At times, you do not want to handle numbers but words. R also has functions for that.

Function Description
substr(x, start=n1, stop=n2) Extract or replace substrings in a character vector
grep(pattern, x , ignore.case=FALSE, fixed=FALSE) Search for pattern in x
sub(pattern, replacement, x, ignore.case =FALSE, fixed=FALSE) Find pattern in x and replace with replacement text
strsplit(x, split) Split the elements of character vector x at split
paste(…, sep=’’) Concatenate strings

Lets try a few examples:

a="camilo1989" #here I have a character variable, but want to remove that number, so
b=gsub("1989", "", a) #here I replace the value indicated in between the first quotations, for what is in between the second quotations, in this case nothing.
b
## [1] "camilo"
Characters are always between quotations and this is done to differentiate from variable names. Say I have a variable I called data but I also have a word I want to use called data as well. In this case data by ilfset will be the database, but “data” will be recongnized as chracaters. Later on we will get to this.

The function paste is another function that you will use a lot.

a="camilo" #here I have a character variable, that I want to concatenate with another one. 
b="1989" #second variable.
c=paste(a,b,sep="_") #here I merge a and b, and separate them with an underscore
c
## [1] "camilo_1989"

If you want nothing to separate the words, put nothing between the brackets in sep, like this

c=paste(a,b,sep="")
c
## [1] "camilo1989"