# creating matrix using matrix()
= matrix(
A c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
) A
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
(AST230) R for Data Science
Until now, you’ve created fairly simple data in R and stored it as a vector.
However, most (if not all) of you will have much more complicated datasets from your various experiments and surveys that go well beyond what a vector can handle.
In previous lectures we’ve gone through the main four data types (i.e vector types) in R, i.e. logical, integer, double, character
Now let’s have a look at some of main structures that we have for storing these data.
1. Atomic vectors
2. Matrices
3. Arrays
4. Factors
5. Lists
6. Data frames
7. Tibbles
When a rectangular data structure contains a single type of data in all its cells (i.e., in all its rows and columns), we have a matrix of data.
In R, a matrix really is an atomic vector that is tweaked into another shape (i.e., a re-shaped vector).
Internally, this is implemented by taking a vector and adding attributes that describe its shape and the names of its rows or columns
matrix()
is used to create a matrix from a atomic vector.Summary:
Like vectors and matrices, arrays must contain elements all of the same data types.
Data structures like matrices, or arrays are built on top of atomic vectors by adding attributes
In other words, matrices and arrays are just atomic vectors with a dim()
(dimension) attribute
%*%
operator to perform matrix multiplication.R has numerous built in functions to perform matrix operations
For example, to transpose a matrix we use the transposition function t()
diag()
function.Functions | Description |
---|---|
chol(x) |
Choleski decomposition |
t(x) |
Transpose of a matrix x. |
diag(x) |
Extracts the diagonal elements of a matrix |
ncol(x) |
Returns the number of columns |
nrow(x) |
Returns the number of rows |
colSums(x) |
Returns the sum of columns |
rowSums(x) |
Returns the sum of rows |
solve(A,b) |
Solve the system A x=b |
solve(x) |
Calculate the inverse |
Create a vector called x
consisting of the first fifteen integers of the number line.
Use the function dim()
to assign dimension to vector x
with three rows and five columns. What is the class of x
now?
Given the following matrices, A=\left[\begin{array}{llll} 2 & 9 & 0 & 0 \\ 0 & 4 & 1 & 4 \\ 7 & 5 & 5 & 1 \\ 7 & 8 & 7 & 4 \end{array}\right] \quad b=\left[\begin{array}{c} -1 \\ 6 \\ 0 \\ 9 \end{array}\right]
Generate a vector x0
of order 20 with all elements as 1
Generate a vector x1
of order 20 with elements randomly selected from 30:70, consider a seed 80
Create a matrix X
with the first column x0
and the second column x1
Generate a vector Y
of order 20 using the equation y_i = 1.2 + 1.8x1 + \epsilon_i, where \epsilon_i\sim N(0, 9)
Obtain the value of (X'X)^{-1}X'Y, use the R function solve()
to obtain an inverse of a square matrix.
Remember: matrices, arrays are just atomic vectors that are reshaped
In addition to these regular atomic vectors, there are some S3 atomic vectors
One of the most important vector attributes is class
, which underlies the S3 object system
A class attribute turns an object into an S3 object, which means it will behave differently from a regular vector when passed to a generic function
Every S3 object is built on top of a base type, and often stores additional information in other attributes
Some important S3 vectors used in base R are
Categorical data recorded in factor
vector
Dates are stored in Date
vector
Date-times are stored in POSIXct
and POSIXlt
vectors
Among these, we will discuss only the factor
vector.
Factors are used to store categorical information in R, a categorical variable has only pre-defined levels, e.g., gender has two levels male
and female
Factors are similar to character
data except it can take only predefined values
Factors are built on top of an integer vector with two attributes:
a class, “factor”, which makes it behave differently from regular integer vectors, and
levels, which defines the set of allowed value
Factors look like strings, but behave like integers
The function factor()
is used to create factor vector from an atomic vector and it has the following arguments
x
\rightarrow data vector
levels
\rightarrow values of x
that will be used as the level of the factor
labels
\rightarrow a vector of labels for the levels
# not providing levels
fac1 = factor(c("Male", "Female", "Male",
"Male", "Female", "Male", "Female"))
fac1
[1] Male Female Male Male Female Male Female
Levels: Female Male
# providing levels
fac2 = factor(c("Male", "Female", "Male",
"Male", "Female", "Male", "Female"),
levels = c("Male", "Female"))
fac2
[1] Male Female Male Male Female Male Female
Levels: Male Female
List is a vector with heterogeneous elements, i.e., each element of a list can be any type
The function list()
is used to create a list
List of 1
$ :List of 1
..$ :List of 1
.. ..$ : chr "First list"
Recall: Data structures like matrices, arrays, or factors are built on top of atomic vectors by adding attributes.
Similarly, in addition to the regular lists, there are two important S3 vectors built on top of lists
A data frame is a named list of vectors with attributes for (column) names
, row.names
, and its class
, “data.frame”
In contrast to a regular list, a data frame has an additional constraint:
This gives data frames their rectangular structure
Columns are variables, and rows are observations
Data frame is R’s equivalent to spreadsheet
If you do data analysis in R, you’re going to be using data frames
data.frame()
is used to create a new data frame, where atomic vectors can be used as inputsas.data.frame()
There are various ways to inspect a data frame, such as:
str()
gives a very brief description of the datanames()
gives the name of each variable in the datasummary()
gives some very basic summary statistics for each variablehead()
shows the first few rowstail()
shows the last few rowsData frame is one of the most important ideas in R and it is one of the things that make R different from other programming languages
Data frames are created more than 20 years ago and over the years, the way people use R have changed
Some of the design decisions of data frame do not go well with current way of using R
Tibbles are similar to data frames and it overcome some of limitations of data frames
Tibbles are not the part of the base R, it is in the R package tibble
To use tibble, one need to load the package tibble
to the current R environment
# Load the tibble package
library(tibble)
# Create a tibble with three columns: name, age, and city
my_data <- tibble(
name = c("Samir", "Amir", "Aman"),
age = c(25, 30, 35),
city = c("Dhaka", "Khulna", "Jashore")
)
my_data
# A tibble: 3 × 3
name age city
<chr> <dbl> <chr>
1 Samir 25 Dhaka
2 Amir 30 Khulna
3 Aman 35 Jashore
Data frame
Data frame
mtcars
is available in base R mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
# A tibble: 32 × 11
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 21 6 160 110 3.9 2.62 16.5 0 1 4 4
2 21 6 160 110 3.9 2.88 17.0 0 1 4 4
3 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1
4 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
5 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2
6 18.1 6 225 105 2.76 3.46 20.2 1 0 3 1
7 14.3 8 360 245 3.21 3.57 15.8 0 0 3 4
8 24.4 4 147. 62 3.69 3.19 20 1 0 4 2
9 22.8 4 141. 95 3.92 3.15 22.9 1 0 4 2
10 19.2 6 168. 123 3.92 3.44 18.3 1 0 4 4
# ℹ 22 more rows