library(tidyverse)## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.1.7 ✔ dplyr 1.0.9
## ✔ tidyr 1.2.0 ✔ stringr 1.4.0
## ✔ readr 2.1.2 ✔ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
# An addition
5 + 5 ## [1] 10
# A subtraction
5 - 5 ## [1] 0
# A multiplication
3 * 5## [1] 15
# A division
(5 + 5) / 2 ## [1] 5
# Exponentiation
3^2## [1] 9
# Modulo
5%%3## [1] 2
Use the notations <- or -> to assign a value to a variable. The arrow must point to the variable.
a <- 2
3 -> b
v = 3Variables are cAsE sEnSiTiVe:
a <- 3
A <- 4
a==A## [1] FALSE
You cannot sum a numeric and a character variable
c <- 4
d <- "hola"
c+d## Error in c + d: argumento no-numérico para operador binario
Decimal values like 4.5 are called numerics.
Whole numbers like 4 are called integers.
Integers are also numerics.
Boolean values (TRUE or
FALSE) are called logical.
Text (or string)
values are called characters.
Use class()
c## [1] 4
class(c)## [1] "numeric"
d## [1] "hola"
class(d)## [1] "character"
Turning character values into Numeric:
vect <- c("1","2","3")
vect #here you see character values## [1] "1" "2" "3"
vect <- as.numeric(vect)
vect #here you see numeric values## [1] 1 2 3
NULL #Null value## NULL
NA #Absent value## [1] NA
NA + 1 #Guess what will happen## [1] NA
Vectors (one dimensional array): can hold numeric,
character or logical values. The elements in a vector all have the same
data type.
Matrices (two dimensional array): can
hold numeric, character or logical values. The elements in a matrix all
have the same data type.
Data frames
(two-dimensional objects): can hold numeric, character or logical
values. Within a column all elements have the same data type, but
different columns can be of different data type. Lists:
can hold matrices, vectors, data frames, even other lists. # Vectors
Vectors are one-dimension arrays that can hold numeric data,
character data, or logical data. Basically, a simple tool to store
data.
In R, you create a vector with the combine function
c().
Remember, to create a vector, use the function c()
datos <- c(5.3,8.6,4.2)
datos## [1] 5.3 8.6 4.2
datos2 <- c(4.4,5.3)
datos2## [1] 4.4 5.3
You can even use a vector as part of a new vector
datos3 <- c(datos,2.2,3.5)
datos3## [1] 5.3 8.6 4.2 2.2 3.5
especies <- c("tortuga","gato","raton")
str(especies) #str() shows the structure of the object## chr [1:3] "tortuga" "gato" "raton"
Now… What would happen if we mix numeric values with characters in a vector???
especies2 <- c(especies,4,5,7)Print especies2 and you will see that numbers are into quotes, meaning they are characters, not numeric values
especies2## [1] "tortuga" "gato" "raton" "4" "5" "7"
Boolean_vector <- c(TRUE, FALSE, TRUE)
str(Boolean_vector) #let's see the structure## logi [1:3] TRUE FALSE TRUE
Now… If you put numeric with logical values mixed
f <- c(TRUE,FALSE,TRUE,1,2)
f #remember, system reads FALSE as 0 and TRUE as 1## [1] 1 0 1 1 2
Everything will be numeric.
The two commands executed below, will do the same action:
seq(1,10)## [1] 1 2 3 4 5 6 7 8 9 10
1:10## [1] 1 2 3 4 5 6 7 8 9 10
Then, why would we use seq()?, well… it can go sequentially (2by2, 3by3, etc)
seq(1,10, by=2)## [1] 1 3 5 7 9
You can give a name to the elements of a vector with the names() function. Have a look at this example:
poker_vector <- c(140, -50, 20, -120, 240)
names(poker_vector) <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")This code first creates a vector poker_vector and then gives the five elements a name. The first element is assigned the name Monday, while the second element is labeled Tuesday and so on. If your print a named vector, it will show
poker_vector## Monday Tuesday Wednesday Thursday Friday
## 140 -50 20 -120 240
There is a more efficient way to do this, namely, to assign the days of the week vector to a variable!
roulette_vector <- c(-24, -50, 100, -350, 10)
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
names(roulette_vector) <- days_vector
roulette_vector## Monday Tuesday Wednesday Thursday Friday
## -24 -50 100 -350 10
Another example
Let’s assign a name to each position of the datos5 vector:
datos5 <- c(4.3,4.6,8.3,9.4,5.1,6.2)
datos5 #No names have been assigned yet## [1] 4.3 4.6 8.3 9.4 5.1 6.2
names(datos5) <- c("a","b","c","d","e","f")
datos5 #Now see the names. Carefull, It's not an extra row!## a b c d e f
## 4.3 4.6 8.3 9.4 5.1 6.2
Now, this is how you call a vector using the position name
datos5["d"]## d
## 9.4
datos5["d"] + datos5["e"]## d
## 14.5
First Leeson. You Cannot sum, substract, multiply or divide Character values, that would display an error.
a_numeric_vector <- c(1,2,3,4,5)
a_character_vector <- c("a", "b", "c", "d", "e")
a_numeric_vector + a_character_vector## Error in a_numeric_vector + a_character_vector: argumento no-numérico para operador binario
This is simple… It will sum component by component
A_vector <- c(1, 2, 3)
B_vector <- c(4, 5, 6)
total_vector <- A_vector + B_vector
total_vector## [1] 5 7 9
But, what if the vectors are not of the same size?
datos <- c(5.3,8.6,4.2)
datos3 <- c(datos,2.2,3.5)
datos + datos3## Warning in datos + datos3: longitud de objeto mayor no es múltiplo de la
## longitud de uno menor
## [1] 10.6 17.2 8.4 7.5 12.1
#Be careful with the operation performed here. Since [datos] has 3 elements and [datos3] has 5 elements, sum is not mathematically possible,however R does something different, it will restart the [datos] vector and continue summing with [datos3] component by component-This is what R just did: datos + datos3 = (datos[1]+datos3[1]), (datos[2]+datos3[2], (datos[3]+datos3[3]), (datos[1]+datos3[4]), (datos[2]+datos3[5]))
You must call objects into a vector using their position. This is possible using their index
datos3## [1] 5.3 8.6 4.2 2.2 3.5
datos3[1] #selecting element number 1## [1] 5.3
datos3[c(1, 2, 3)] #this is how to select multiple elements: 1, 2, 3 in this case## [1] 5.3 8.6 4.2
datos3[c(1:3)] #same selection than above, but abbreviated## [1] 5.3 8.6 4.2
datos3[c(2,4)] #selecting element 2 and element 4## [1] 8.6 2.2
datos3[c(2,2,2,3,3,3)] #Here you choose 2 three times and 3 three times## [1] 8.6 8.6 8.6 4.2 4.2 4.2
To assign a different value to an item contained into a vector, you must call its position and then assign the new value
datos3## [1] 5.3 8.6 4.2 2.2 3.5
datos3[2] <- "Now i am text lol"
datos3## [1] "5.3" "Now i am text lol" "4.2"
## [4] "2.2" "3.5"
datos4 <- c(5,6,7,8,9,10)What would happen if you call a negative index?
datos4[-2]## [1] 5 7 8 9 10
Yes… It will print the vector without that specific index that you
mentioned.
You can even do it with multiple positions at
the same time:
datos4[-c(2,3,4)]## [1] 5 9 10
This won’t work:
datos4[c(-1,2)]## Error in datos4[c(-1, 2)]: solamente 0's pueden ser mezclados con subscritos negativos
Let’s Use this vector:
datos4## [1] 5 6 7 8 9 10
Notice this command. It will just print the positions whose values corresponds to TRUE… the vector will start alternating among TRUE & FALSE infinitely:
datos4[c(TRUE,FALSE)] ## [1] 5 7 9
Now we will use a Logical vector to selectively call items from datos4
datos4[c(T, F, F, T, T, F)]## [1] 5 8 9
If you use a condition in a vector, it will return a Logical vector of the same size
datos4<7## [1] TRUE TRUE FALSE FALSE FALSE FALSE
You can even try multiple conditions at the same time
datos4<7 | datos4>8## [1] TRUE TRUE FALSE FALSE TRUE TRUE
Now lets subset a vector using a Logical vector created using multiple conditions
datos4## [1] 5 6 7 8 9 10
datos4[datos4>5 & datos4<9]## [1] 6 7 8
This is VERY USEFUL to SUBSET VECTORS USING
CONDITIONS. Filters operate like this
Now… What happens if you try to operate with logical
vectors?
sum(datos4 < 7)## [1] 2
Just two elements met the condition. In other words, just two
elements were TRUE
Yes… TRUE will be considered as 1 and FALSE as 0.
and R will turn the logical vector as a numeric
vector
This is how yo sort a vector:
datos6 <- c(4.3,4.6,8.3,9.4,5.1,6.2)
sort(datos6,decreasing = TRUE)## [1] 9.4 8.3 6.2 5.1 4.6 4.3
rep(m, n): It will take m and repeat it n times
rep(1, 5)## [1] 1 1 1 1 1
It doesn’t matter if it’s a vector:
rep(1:3, 5)## [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
x = rnorm(n=10000, mean = 3, sd = 0.5)
mean(x)## [1] 2.999759
sd(x)## [1] 0.5027209
hist(x)Factor turns a vector into a nominal categorical Variable:
g <- c("a","b","c","c","c","b") #this is a vector of characters... as you have seen before
summary(g)## Length Class Mode
## 6 character character
Now let’s turn that into a factor
g <- factor(g)
summary(g) #you can see now that "a", "b", "c" were transformed into categories## a b c
## 1 2 3
The categories shown above are “a”, “b”, “c”. They don´t have
an specified order, meaning we can´t say a>b or b<c (that
would not make sense for nominal categorical
variable).
What if you would like to set an order
among the categories? Welcome to the Ordinal Categorical
variable
Consider for example the categorical variable
speed_vector with the categories: “slow”, “medium” and
“fast”. Of course “slow”<“medium”<“fast”. This
order is what defines these as Ordinal Categorical
Variables
speed_vector <- c("medium", "slow", "slow", "medium", "fast")If we just do:
factor(speed_vector)
It will not have an
order, so it will still be a Nominal Categorical
Variable:
factor_speedvector <- factor(speed_vector)
str(factor_speedvector) #Let´s see the structure## Factor w/ 3 levels "fast","medium",..: 2 3 3 2 1
Then if we want to set an order on these, we have to use two arguments inside factor(); ordered and levels
factor_ordered_speedvector <- factor(speed_vector, ordered=T, levels=c("slow", "medium", "fast"))
str(factor_ordered_speedvector) #Let´s see the structure## Ord.factor w/ 3 levels "slow"<"medium"<..: 2 1 1 2 3
By setting the argument ordered to
TRUE in the function factor(), you
indicate that the factor is ordered. This argument is the
one that transforms this into an Ordinal Categorial
Variable
With the argument
levels you give the values of the factor in the correct
order.
If you want to compare two categories, these must be ordered. Must be an ordered factor
factor_ordered_speedvector[1] > factor_ordered_speedvector[5]## [1] FALSE
Of course “medium” is not greater than “fast”, we made sure that didn´t happen ;)
When you first get a dataset, you will often notice that it contains
factors with specific factor levels. However, sometimes you will want to
change the names of these levels for clarity or other reasons. R allows
you to do this with the function levels():
Structure: levels(factor_vector) <- c(“name1”,
“name2”,…)
sex_vector <- c("M", "F", "F", "M", "M") #Here, for simplicity, just two categories were recorded, "M" and "F"
factor_sexvector <- factor(sex_vector)
factor_sexvector #Notice the order of the levels below. Spoiler: R creates them alphabetically## [1] M F F M M
## Levels: F M
Recording the sex with the abbreviations “M” and “F” can be
convenient, but you can be more clear. you may want to change the factor
levels to “Male” and “Female” instead of “M” and “F” for
clarity.
Careful!!! These names
should be in the same order than the levels. See the spoiler note in
the code above for clarity
levels(factor_sexvector) <- c("Female", "Male")
factor_sexvector## [1] Male Female Female Male Male
## Levels: Female Male
Your levels are changed now :)
A data frame has the variables of a dataset as columns and the observations as rows. The difference with a Matrix, is that in the DF you can put different data types (numeric, character, logical)
a <- c(3, 2, 1, 4)
b <- c("f","f","m","f")
c <- c(2.3, 4.6, 3.8, 3.1)
datos <- data.frame(a,b,c)
datosTo call a specific column in a dataframe, use $ followed by the column´s name:
datos$b## [1] "f" "f" "m" "f"
We can even transform a column into a Factor:
datos$b <- factor(datos$b)
str(datos) #1st and 3rd column are Numeric, 2nd is a Factor## 'data.frame': 4 obs. of 3 variables:
## $ a: num 3 2 1 4
## $ b: Factor w/ 2 levels "f","m": 1 1 2 1
## $ c: num 2.3 4.6 3.8 3.1
summary(datos) #summary in a numeric column, shows Min value, Max value, Mean, Median, etc... in a Factor column it only shows each category and its frequency## a b c
## Min. :1.00 f:3 Min. :2.30
## 1st Qu.:1.75 m:1 1st Qu.:2.90
## Median :2.50 Median :3.45
## Mean :2.50 Mean :3.45
## 3rd Qu.:3.25 3rd Qu.:4.00
## Max. :4.00 Max. :4.60
let´s call some rows and columns from datos
datosdatos [2, ] #here i am calling the entire second rowdatos [, 2] #and here the entire second column## [1] f f m f
## Levels: f m
datos[,c("a","b")] #here we are calling two columns by their name... Why columns? they are after the comma.datos$b[4] #This is more specific, the fourth item from the "b" column## [1] f
## Levels: f m
datosdatos$d <- c(T,T,F,F)
datosConsider two DataFrames
datos #printing out datosdatos2 <- data.frame(f=c(20,21,23,25), e=c("s","p","s","s"))
datos2 #printing out datos2datos_1 <- cbind(datos,datos2) #this is how you join them
datos_1str(datos_1)## 'data.frame': 4 obs. of 6 variables:
## $ a: num 3 2 1 4
## $ b: Factor w/ 2 levels "f","m": 1 1 2 1
## $ c: num 2.3 4.6 3.8 3.1
## $ d: logi TRUE TRUE FALSE FALSE
## $ f: num 20 21 23 25
## $ e: chr "s" "p" "s" "s"
summary(datos_1)## a b c d f
## Min. :1.00 f:3 Min. :2.30 Mode :logical Min. :20.00
## 1st Qu.:1.75 m:1 1st Qu.:2.90 FALSE:2 1st Qu.:20.75
## Median :2.50 Median :3.45 TRUE :2 Median :22.00
## Mean :2.50 Mean :3.45 Mean :22.25
## 3rd Qu.:3.25 3rd Qu.:4.00 3rd Qu.:23.50
## Max. :4.00 Max. :4.60 Max. :25.00
## e
## Length:4
## Class :character
## Mode :character
##
##
##
head(m, n) prints the first n Rows in the
m Dataframe.
head(mtcars, 5) #mtcars is a DF loaded in R by defaulttail(m, n) prints the last n Rows in the
m Dataframe.
tail(mtcars, 5)Shows the structure of the dataset, with str() you can see:
-The total number of observations
Rows(e.g. 32 car types)
-The total number of variables Columns(e.g. 11
car features)
-A full list of the variables names Col
names(e.g. mpg, cyl … )
-The data type of each variable (e.g. num)
-The first observations
str(mtcars)## 'data.frame': 32 obs. of 11 variables:
## $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
## $ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
## $ disp: num 160 160 108 258 360 ...
## $ hp : num 110 110 93 110 175 105 245 62 95 123 ...
## $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
## $ wt : num 2.62 2.88 2.32 3.21 3.44 ...
## $ qsec: num 16.5 17 18.6 19.4 17 ...
## $ vs : num 0 0 1 1 0 1 0 1 1 1 ...
## $ am : num 1 1 1 0 0 0 0 0 0 0 ...
## $ gear: num 4 4 4 3 3 3 3 4 4 4 ...
## $ carb: num 4 4 1 1 2 1 4 2 2 4 ...
To sort, you must understand the function
order():
order() gives you the ranked position of each
element
a <- c(100, 10, 1000)
order(a)## [1] 2 1 3
#Note that it will give you a vector with the positions organized (increasing)Now, to reshuffle a, you must use
a[order(a)]## [1] 10 100 1000
Let´s do Another example
#Consider this DF
name <- c("Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune")
type <- c("Terrestrial planet",
"Terrestrial planet",
"Terrestrial planet",
"Terrestrial planet", "Gas giant",
"Gas giant", "Gas giant", "Gas giant")
diameter <- c(0.382, 0.949, 1, 0.532,
11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03,
0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
# Create a data frame from the vectors
planets_df <- data.frame(name, type, diameter, rotation, rings)
planets_df#Now let´s sort by diameter
order(planets_df$diameter)## [1] 1 4 2 3 8 7 6 5
planets_df[order(planets_df$diameter), ]Collection of elements of the same data type (numeric,
character, or logical) arranged into a fixed number of
rows and columns.
You can construct a matrix in R with the matrix() function.
Consider the following example:
#Notice that here it will be organized by row
matrix(1:9, byrow = TRUE, nrow = 3)## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] 4 5 6
## [3,] 7 8 9
#And here it is organized by columns
matrix(1:9, byrow = FALSE, nrow = 3)## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
The first argument is the collection of
elements that R will arrange into the rows and columns of the matrix.
Here, we use 1:9 which is a shortcut for c(1, 2, 3, 4, 5, 6, 7, 8,
9).
The argument byrow indicates that the matrix is
filled by the rows. If we want the matrix to be filled by the columns,
we just place byrow = FALSE.
The third argument nrow indicates that the matrix
should have three rows.
In the editor, three vectors are defined. you’ll combine these three vectors into a single vector. Next, you’ll build a matrix from this new vector.
# Original three vectors
v1 <- c(460.998, 314.4)
v2 <- c(290.475, 247.900)
v3 <- c(309.306, 165.8)
# Combine the three vectors
v123 <- c(v1, v2, v3)
v123## [1] 460.998 314.400 290.475 247.900 309.306 165.800
# Construct the matrix
matrixxx <- matrix(v123, nrow = 3, byrow=T)
matrixxx## [,1] [,2]
## [1,] 460.998 314.4
## [2,] 290.475 247.9
## [3,] 309.306 165.8
Consider the matrix from the previous exercise
#let´s consider the matrix below
matrixxx## [,1] [,2]
## [1,] 460.998 314.4
## [2,] 290.475 247.9
## [3,] 309.306 165.8
Naming rows
To name the rows, use
rownames
#The amount of names that you assign, must be equal to the amount of rows that the matrix has
rownames(matrixxx) <- c("firstrow", "secondrow", "third row")Naming Columns
To name the columns, use
colnames
#The amount of names that you assign, must be equal to the amount of columns that the matrix has
colnames(matrixxx) <- c("fistcol", "secondcol")See the names that you just put
matrixxx## fistcol secondcol
## firstrow 460.998 314.4
## secondrow 290.475 247.9
## third row 309.306 165.8
Analyze the code below if you want to name a matrix faster:
# Construct star_wars_matrix
box_office <- c(460.998, 314.4, 290.475, 247.900, 309.306, 165.8)
region <- c("US", "non-US")
titles <- c("A New Hope",
"The Empire Strikes Back",
"Return of the Jedi")
star_wars_matrix <- matrix(box_office,
nrow = 3, byrow = TRUE,
dimnames = list(titles, region))
star_wars_matrix## US non-US
## A New Hope 460.998 314.4
## The Empire Strikes Back 290.475 247.9
## Return of the Jedi 309.306 165.8
rowSums() is a helpful function that creates a vector which contains the sum of your rows.
star_wars_matrix## US non-US
## A New Hope 460.998 314.4
## The Empire Strikes Back 290.475 247.9
## Return of the Jedi 309.306 165.8
# Get the sum of each row
worldwide_vector <- rowSums(star_wars_matrix)
worldwide_vector## A New Hope The Empire Strikes Back Return of the Jedi
## 775.398 538.375 475.106
colSums() allows you to do the same action than rowSums(), but in the columns
the cbind() function allows you to add a column or multiple columns to a matrix. It merges matrices and/or vectors together by column.
#consider this matrix
star_wars_matrix## US non-US
## A New Hope 460.998 314.4
## The Empire Strikes Back 290.475 247.9
## Return of the Jedi 309.306 165.8
#and this vector
worldwide_vector## A New Hope The Empire Strikes Back Return of the Jedi
## 775.398 538.375 475.106
#Let´s Join!
all_wars_matrix <- cbind(star_wars_matrix, worldwide_vector)
all_wars_matrix## US non-US worldwide_vector
## A New Hope 460.998 314.4 775.398
## The Empire Strikes Back 290.475 247.9 538.375
## Return of the Jedi 309.306 165.8 475.106
the rbind() function allows you to add a column or multiple columns to a matrix. It merges matrices and/or vectors together by column.
you can use [] to select elements from a matrix (a single one or many
of them at the same time if you want), since the matrix is 2D, you have
to put two coordinates in the [].
Structure:
my_matrix[1,2] selects the element at the first
row and second column.
my_matrix[1:3,2:4] results
in a matrix with the data on the rows 1, 2, 3 and columns 2, 3, 4.
my_matrix[,1] selects all elements of the first
column.
my_matrix[1,] selects all elements of the
first row.
A list in R allows you to gather a variety of objects under one name
(that is, the name of the list) in an ordered way. These objects can be
matrices, vectors, data frames, even other lists, etc. It is not even
required that these objects are related to each other in any way.
You could say that a list is some kind super data type: you can store
practically any piece of information in it!
Let´s build a list!
#This list will contain a vector, a matrix and a dataframe
# Vector with numerics from 1 up to 10
my_vector <- 1:10
# Matrix with numerics from 1 up to 9
my_matrix <- matrix(1:9, ncol = 3)
# First 10 elements of the built-in data frame mtcars
my_df <- mtcars[1:10,]
# Construct list with these different elements:
my_list <- list(my_vector, my_matrix, my_df)
#let´s print!
my_list## [[1]]
## [1] 1 2 3 4 5 6 7 8 9 10
##
## [[2]]
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
##
## [[3]]
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
## Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
## Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
## Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
## Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
You can name each element in a list
str:
my_list <- list(name1 = your_comp1, name2 = your_comp2)
This creates a list with components that are named name1, name2, and so on. If you want to name your lists after you’ve created them, you can use the names() function as you did with vectors. The following commands are fully equivalent to the assignment above:
my_list <- list(your_comp1, your_comp2) names(my_list) <- c(“name1”, “name2”)
#Use for my_vector the name vec, for my_matrix the name mat and for my_df the name df.
my_list <- list(vec = my_vector, mat = my_matrix, df = my_df)
my_list## $vec
## [1] 1 2 3 4 5 6 7 8 9 10
##
## $mat
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
##
## $df
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
## Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
## Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
## Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
## Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
To select a component, use the numbered position of that component. For example, to “grab” the first component of my_list you type:
my_list[[1]]## [1] 1 2 3 4 5 6 7 8 9 10
You can also refer to the names of the components, with [[ ]] or with the $ sign. Important to remember: to select elements from vectors, you use single square brackets: [ ]. Don’t mix them up!
my_list[["mat"]] #we´re calling the second element from my_list## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
my_list$mat## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
After using the [[]] to call an element, you can call an element of
that element.
For example in the matrix “mat”, it wold be:
my_list[["mat"]][2,3]## [1] 8
@Datacamp - Introduction to R
Code end