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:
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.
## [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
## [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"
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
## [1] "camilo1989"