Professional Documents
Culture Documents
Pertemuan R Ke 02
Pertemuan R Ke 02
Operators are used to perform operations on values and variables. The R operators are
classified into six different categories:
Arithmetic operators
Comparison operators
Logical operators
Element-wise Logical operators
Membership operators
Assignment operators
Arithmetic Operators
Arithmetic operators are used to perform simple mathematical operations on numeric values
and vectors.
Operator Meaning Example
+ Addition x+y
– Subtraction x–y
* Multiplication x*y
/ Division x/y
%% Modulus x %% y
^ Exponents x^y
%/% Integer division x %/% y
All the basic arithmetic operators can be performed on pairs of vectors. Each operation is
performed in an element-by-element manner.
Comparison Operators
Comparison operators are used to compare two values or vectors.
Assignment Operators
Assignment operators are used to assign new values to variables.
Miscellaneous Operators
These operators are used to for special purposes.
Operator Description
highest precedence ({ Function calls and grouping expressions (respectively)
[ [[ Indexing
:: ::: Access variables in a namespace
$@ Component / slot extraction
^ Exponentiation (right to left)
–+ Unary minus and plus
: Sequence operator
%any% Special operators
*/ Multiply, divide
+– (Binary) add, subtract
< > <= >= == != Ordering and comparison
! Negation
& && And
| || Or
~ As in formulas
-> ->> Rightward assignment
= Assignment (right to left)
<- <<- Assignment (right to left)
lowest precedence ? Help (unary and binary)
R Vector
A vector is a collection of elements, all the same type (similar to an array in other
programming languages but more versatile).
When using R, you will frequently encounter the four basic vector types viz. logical,
character, integer and double (often called numeric).
Create a vector
In R, there are several ways to create a new vector; the simplest is to use the c() function.
# integer vector
c(1, 2, 3, 4, 5, 6)
[1] 1 2 3 4 5 6
# double vector
c(1*pi, 2*pi, 3*pi, 4*pi)
[1] 3.141593 6.283185 9.424778 12.566371
# character vector
c("red", "green", "blue")
[1] "red" "green" "blue"
# logical vector
c(TRUE, FALSE, TRUE, FALSE)
[1] TRUE FALSE TRUE FALSE
As a vector contains elements of the same type, if you try to combine different type of
elements, the c() function converts (coerces) them into a single type.
Create a Sequence
You can also create a vector using:
The : Operator
You can generate an equally spaced sequence of numbers, by using the : sequence
operator.
Naming a Vector
Each element of a vector can have a name. It allows you to access individual elements by
names. You can give a name to the vector element with the names() function.
Subsetting Vectors
There are several ways to subset a vector (extract a value from the vector). You can do this
by combining square brackets [] with:
Positive integers
Negative integers
Logical values
Names
Subsetting with positive integers returns the elements at the specified positions. Note that
vector positioning starts from 1.
v <- c("a","b","c","d","e","f")
# select 3rd element
v[3]
[1] "c"
# select 5th element
v[5]
[1] "e"
v <- c("a","b","c","d","e","f")
# select elements from index 2 to 5
v[2:5]
[1] "b" "c" "d" "e"
# select elements from index 1 to 6 by increment 2
v[seq(from=1,to=6,by=2)]
[1] "a" "c" "e"
The indexing vector need not be a simple sequence. You can select elements anywhere
within the vector.
v <- c("a","b","c","d","e","f")
# select 1st, 3rd, 5th and 6th element
v[c(1,3,5,6)]
[1] "a" "c" "e" "f"
v <- c("a","b","c","d","e","f")
# omit first element
v[-1]
[1] "b" "c" "d" "e" "f"
# omit elements from index 2 to 5
v[-2:-5]
[1] "a" "f"
# omit 1st, 3rd and 5th element
v[c(-1,-3,-5)]
[1] "b" "d" "f"
v <- c(1,2,3,4,5,6)
v[c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE)]
[1] 1 3 5
You can also use a logical vector to select elements based on a condition.
v <- c("a","b","c","d","e","f")
v[3] <- 1
v
[1] "a" "b" "1" "d" "e" "f"
You can also modify more than one element at once.
v <- c("a","b","c","d","e","f")
v[1:3] <- c(1,2,3)
v
[1] "1" "2" "3" "d" "e" "f"
Add Elements to a Vector
The c() function can also be used to add elements to a vector.
v <- c(1,2,3)
# Add a single value to v
v <- c(v,4)
v
[1] 1 2 3 4
# Append an entire vector to v
w <- c(5,6,7,8)
v <- c(v,w)
v
[1] 1 2 3 4 5 6 7 8
Vector Arithmetic
Vector operations are one of R’s great strengths. All the basic arithmetic operators can be
performed on pairs of vectors. Each operation is performed in an element-by-element
manner.
v1 <- c(11,12,13,14,15)
v2 <- c(1,2,3,4,5)
# addition
v1 + v2
[1] 12 14 16 18 20
# subtraction
v1 - v2
[1] 10 10 10 10 10
# multiplication
v1 * v2
[1] 11 24 39 56 75
# division
v1 / v2
[1] 11.000000 6.000000 4.333333 3.500000 3.000000
# exponents
v1 ^ v2
[1] 11 144 2197 38416 759375
If one operand is a vector and the other is a scalar, then the operation is performed between
every vector element and the scalar.
v <- c(1,2,3,4,5)
sqrt(v)
[1] 1.000000 1.414214 1.732051 2.000000 2.236068
log(v)
[1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379
If we apply arithmetic operations to two vectors of unequal length, then the elements of the
shorter vector are recycled to match the longest vector.
Sort a Vector
You can sort a vector using the sort() function. You can also specify the order in which you
want to sort a vector.
v <- c(1,2,3,4,5)
length(v)
[1] 5
Calculate Basic Statistics
You can calculate basic statistics by using below simple R functions.
Statistic Function
mean mean(x)
median median(x)
standard deviation sd(x)
variance var(x)
correlation cor(x, y)
covariance cov(x, y)
These functions take a vector of numbers as an argument and return the calculated statistic.
v <- c(1,2,3,4,5,6)
# mean
mean(v)
[1] 3.5
# median
median(v)
[1] 3.5
# standard deviation
sd(v)
[1] 1.870829
# variance
var(v)
[1] 3.5
# correlation
cor(v, 2:7)
[1] 1
# covariance
cov(v, 2:7)
[1] 3.5
R List
Vectors and matrices are incredibly useful data structure in R, but they have one distinct
limitation: they can store only one type of data.
Lists, however, can store multiple types of values at once. A list can contain a numeric
matrix, a logical vector, a character string, a factor object and even another list.
Create a List
Creating a list is much like creating a vector; just pass a comma-separated sequence of
elements to the list() function.
# A list of integers
lst <- list(1, 2, 3)
# A list of characters
lst <- list("red", "green", "blue")
# A list of mixed datatypes
lst <- list(1, "abc", 1.23, TRUE)
The best way to understand the contents of a list is to use the structure function str(). It
provides a compact display of the internal structure of a list.
Nested List
A list can contain sublists, which in turn can contain sublists themselves, and so on. This is
known as nested list or recursive vectors.
You can use [[]] to extract only a single element from a list. Unlike [], [[]] gives you the
element itself.
You can’t use logical vectors or negative numbers as indices when using [[]]
The difference becomes clear when we inspect the structure of the output – one is a
character and the other one is a list.
The difference becomes annoyingly obvious when we cat the value. As you know cat() can
print any value except the structured object.
cat(lst[[1]], "\n")
a
cat(lst[1], "\n")
Error in cat(lst[1], "\n") :
argument 1 (type 'list') cannot be handled by 'cat'
You can modify components using [] as well, but you have to assign a list of components.
By using append() method you can append one or more elements to the list.
By using a logical vector, you can remove list elements based on the condition.
Combine Lists
The c() does a lot more than just creating vectors. It can be used to combine lists into a new
list as well.
For example, you cannot directly compute the mean of list of numbers. In that case, you have to
flatten the list into a vector using unlist() first and then compute the mean of the result.
When using R, you will frequently encounter the four basic matrix types viz. logical,
character, integer and double (often called numeric).
Create a Matrix
You can create a matrix using the matrix() function and specifying the data and the number
of rows and columns to make the matrix.
You don’t have to specify both ncol and nrow. If you specify one, R will know automatically
what the other needs to be.
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
v3 <- c(7, 8, 9)
rbind(v1, v2, v3)
[,1] [,2] [,3]
v1 1 2 3
v2 4 5 6
v3 7 8 9
The cbind() function does something similar. It binds the vectors as columns of a matrix.
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
v3 <- c(7, 8, 9)
cbind(v1, v2, v3)
v1 v2 v3
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
# make it 3x2
dim(m) <- c(3,2)
m
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
# make it 1x6
dim(m) <- c(1,6)
m
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 5 6
You can do this by assigning two element list containing row and column names to the
dimnames attribute.
You can even name the rows and columns while creating a matrix by passing dimnames
argument.
By using the rownames() and colnames() function you can assign row names and column
names separately.
You can use the same dimnames(), colnames() and rownames() functions to print column
names and row names.
Subsetting Matrices
In R, subsetting elements from matrices is much like subsetting elements from vectors.
The only difference is that you now have to specify both the row and the column position, in
the order of [row, column].
When you subset for a single row or a column, the result will always be a vector. To avoid
this you can set the drop argument to FALSE.
Subsetting by Names
Subsetting with names will return the elements having the matching names.
Matrix Operations
The most powerful feature of R is the ease of dealing with matrix operations. Because much
of statistics depend on matrix operations, R perform them in an easy and optimized way:
Matrix transpose
Creating an identity matrix
Scalar multiple of a matrix
Matrix addition and subtraction
Matrix multiplication
Matrix inversion
Matrix Transpose
The transpose of a matrix is simply a flipped version of the original matrix obtained by
switching rows with columns. To transpose a matrix, use t() function.
Matrix Multiplication
Unlike scalar multiplication, matrix multiplication is not a simple element-by-element
calculation, and the standard * operator cannot be used. Instead, you must use R’s matrix
product operator %*%.
Matrix Inversion
The inverse of a matrix can be calculated by using the solve() function.
Matrix Length
You can find the total number of values in a matrix using the length() function.