Vectors

A vector is a list of items that are of the same type.

To combine the list of items to a vector, use the c() function and separate the items by a comma.

Create a vector variable called sports, that combine strings:

# Vector of strings
sports <- c("basketball", "baseball", "football")

# Print sports
sports
## [1] "basketball" "baseball"   "football"

Create a vector that combines numerical values:

# Vector of numerical values
numbers <- c(12344,1234081345,51345345134515)

# Print numbers
numbers
## [1] 1.234400e+04 1.234081e+09 5.134535e+13

To create a vector with numerical values in a sequence, use the : operator:

# Vector with numerical values in a sequence
numbers <- 1:120

# Print numbers
numbers
##   [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
##  [19]  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
##  [37]  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
##  [55]  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
##  [73]  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
##  [91]  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108
## [109] 109 110 111 112 113 114 115 116 117 118 119 120

You can also create numerical values with decimals in a sequence, but note that if the last element does not belong to the sequence, it is not used:

# Vector with numerical decimals in a sequence
numbers1 <- 2.5:12.5
numbers1
##  [1]  2.5  3.5  4.5  5.5  6.5  7.5  8.5  9.5 10.5 11.5 12.5
# Vector with numerical decimals in a sequence where the last element is not used
numbers2 <- 1.9:7.8
numbers2
## [1] 1.9 2.9 3.9 4.9 5.9 6.9

In the example below, we create a vector of logical values:

# Vector of logical values
log_values <- c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE)

log_values
## [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE

Vector Length

To find out how many items a vector has, use the length() function:

movies <- c("Aliens", "DUne", "X-Men")

length(movies)
## [1] 3

Sort a Vector

To sort items in a vector alphabetically or numerically, use the sort() function:

movies <- c("Aliens", "DUne", "X-Men", "Doom", "The Thing")
numbers <- c(133, 323, 57457, 7456345247, 202473656, 226457, 24555)

sort(movies)  # Sort a string
## [1] "Aliens"    "Doom"      "DUne"      "The Thing" "X-Men"
sort(numbers) # Sort numbers
## [1]        133        323      24555      57457     226457  202473656 7456345247

Access Vectors

You can access the vector items by referring to its index number inside brackets []. The first item has index 1, the second item has index 2, and so on:

movies <- c("Aliens", "DUne", "X-Men")

# Access the first item (DUne)
movies[1]
## [1] "Aliens"

You can also access multiple elements by referring to different index positions with the c() function:

movies <- c("Aliens", "DUne", "X-Men", "Doom", "The Thing")

# Access the first and third item (banana and orange)
movies[c(1, 3)]
## [1] "Aliens" "X-Men"

You can also use negative index numbers to access all items except the ones specified:

movies <- c("Aliens", "DUne", "X-Men", "Doom", "The Thing")

# Access all items except for the first item
movies[c(-1)]
## [1] "DUne"      "X-Men"     "Doom"      "The Thing"

Change an Item

To change the value of a specific item, refer to the index number:

movies <- c("Aliens", "DUne", "X-Men", "Doom", "The Thing")

# Change "Aliens" to "Feast"
movies[1] <- "Feast"

# Print fruits
movies
## [1] "Feast"     "DUne"      "X-Men"     "Doom"      "The Thing"

Repeat Vectors

To repeat vectors, use the rep() function:

# Repeat each value:

repeat_each <- rep(c(112,21345135,3132451365164), each = 3)

repeat_each
## [1] 1.120000e+02 1.120000e+02 1.120000e+02 2.134514e+07 2.134514e+07
## [6] 2.134514e+07 3.132451e+12 3.132451e+12 3.132451e+12
# Repeat the sequence of the vector:

repeat_times <- rep(c(152345146,21346134,361346), times = 3)

repeat_times
## [1] 152345146  21346134    361346 152345146  21346134    361346 152345146
## [8]  21346134    361346
# Repeat each value independently:

repeat_indepent <- rep(c(141,21235,31516), times = c(5,2,1))

repeat_indepent
## [1]   141   141   141   141   141 21235 21235 31516

Generating Sequenced Vectors

One of the examples on top, showed you how to create a vector with numerical values in a sequence with the : operator:

numbers <- 1:115

numbers
##   [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
##  [19]  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
##  [37]  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
##  [55]  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
##  [73]  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
##  [91]  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108
## [109] 109 110 111 112 113 114 115

To make bigger or smaller steps in a sequence, use the seq() function:

numbers <- seq(from = 0, to = 100, by = 20)

numbers
## [1]   0  20  40  60  80 100

Note: The seq() function has three parameters: from is where the sequence starts, to is where the sequence stops, and by is the interval of the sequence.

Lists

A list can contain many different data types inside. A list is a collection of data which is ordered and changeable.

To create a list, use list():

# List of strings

movies <- list("Alien", "Terminator", "Robocop")

# Print the list
movies
## [[1]]
## [1] "Alien"
## 
## [[2]]
## [1] "Terminator"
## 
## [[3]]
## [1] "Robocop"

Access Lists

You can access the list items by referring to its index number, inside brackets. The first item has index 1, the second item has index 2, and so on:

movies <- list("Alien 3", "Terminator 2", "Robocop")

movies[1]
## [[1]]
## [1] "Alien 3"

Change Item Value

To change the value of a specific item, refer to the index number:

movies <- list("Alien 3", "Terminator 2", "Robocop")
movies[1] <- "Alien"

# Print the updated list
movies
## [[1]]
## [1] "Alien"
## 
## [[2]]
## [1] "Terminator 2"
## 
## [[3]]
## [1] "Robocop"

List Length

To find out how many items a list has, use the length() function:

movies <- list("Alien 3", "Terminator 2", "Robocop", "Total Recall")

length(movies)
## [1] 4

Check if Item Exists

To find out if a specified item is present in a list, use the %in% operator:

# Check if "aAlien 3" is present in the list
movies <- list("Alien 3", "Terminator 2", "Robocop")

"Alien 3" %in% movies
## [1] TRUE

Add List Items

To add an item to the end of the list, use the append() function:

# Add "Avatar" to the list
movies <- list("Alien 3", "Terminator 2", "Robocop")

append(movies, "Avatar")
## [[1]]
## [1] "Alien 3"
## 
## [[2]]
## [1] "Terminator 2"
## 
## [[3]]
## [1] "Robocop"
## 
## [[4]]
## [1] "Avatar"

To add an item to the right of a specified index, add “after=index number” in the append() function:

# Add "X-Files" to the list after "Terminator 2" (index 2)
movies <- list("Alien 3", "Terminator 2", "Robocop")

append(movies, "X-Files", after = 2)
## [[1]]
## [1] "Alien 3"
## 
## [[2]]
## [1] "Terminator 2"
## 
## [[3]]
## [1] "X-Files"
## 
## [[4]]
## [1] "Robocop"

Remove List Items

You can also remove list items. The following example creates a new, updated list without an “Alien 3” item:

# Remove "Alien 3" from the list:

movies <- list("Alien 3", "Terminator 2", "Robocop")

new_movies_list <- movies[-1]

# Print the new list
new_movies_list
## [[1]]
## [1] "Terminator 2"
## 
## [[2]]
## [1] "Robocop"

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range, by using the : operator:

# Return the second, third, fourth and fifth item:

movies <- list("Halloween", "The Goonies", "Total Recall", "The Abyss", "Nightmare on Elm Street", "Friday the 13th", "Coraline")

(movies)[2:5]
## [[1]]
## [1] "The Goonies"
## 
## [[2]]
## [1] "Total Recall"
## 
## [[3]]
## [1] "The Abyss"
## 
## [[4]]
## [1] "Nightmare on Elm Street"

Note: The search will start at index 2 (included) and end at index 5 (included).

Remember that the first item has index 1.

Loop Through a List

You can loop through the list items by using a for loop:

# Print all items in the list, one by one:

movies <- list("Halloween", "The Goonies", "Total Recall", "The Abyss", "Nightmare on Elm Street", "Friday the 13th", "Coraline")

for (x in movies) {
  print(x)
}
## [1] "Halloween"
## [1] "The Goonies"
## [1] "Total Recall"
## [1] "The Abyss"
## [1] "Nightmare on Elm Street"
## [1] "Friday the 13th"
## [1] "Coraline"

Join Two Lists

There are several ways to join, or concatenate, two or more lists in R.

The most common way is to use the c() function, which combines two elements together:

list1 <- list("abc", "def", "ghi")
list2 <- list(111,222,333)
list3 <- c(list1,list2)

list3
## [[1]]
## [1] "abc"
## 
## [[2]]
## [1] "def"
## 
## [[3]]
## [1] "ghi"
## 
## [[4]]
## [1] 111
## 
## [[5]]
## [1] 222
## 
## [[6]]
## [1] 333

#Matrices

A matrix is a two dimensional data set with columns and rows.

A column is a vertical representation of data, while a row is a horizontal representation of data.

A matrix can be created with the matrix() function. Specify the nrow and ncol parameters to get the amount of rows and columns:

# Create a matrix
matrix1 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, ncol = 2)
## Warning in matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 2): data
## length [9] is not a sub-multiple or multiple of the number of columns [2]
# Print the matrix
matrix1
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6

Note: Remember the c() function is used to concatenate items together.

You can also create a matrix with strings:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss"), nrow = 2, ncol = 2)

movies_matrix
##      [,1]          [,2]          
## [1,] "Halloween"   "Total Recall"
## [2,] "The Goonies" "The Abyss"

Access Matrix Items

You can access the items by using [ ] brackets. The first number “1” in the bracket specifies the row-position, while the second number “2” specifies the column-position:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss"), nrow = 2, ncol = 2)

movies_matrix[1, 2]
## [1] "Total Recall"

The whole row can be accessed if you specify a comma after the number in the bracket:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss"), nrow = 2, ncol = 2)

movies_matrix[2, 1]
## [1] "The Goonies"

The whole column can be accessed if you specify a comma before the number in the bracket:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss"), nrow = 2, ncol = 2)

movies_matrix[, 2]
## [1] "Total Recall" "The Abyss"

Access More Than One Row

More than one row can be accessed if you use the c() function:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss", "Nightmare on Elm Street", "Friday the 13th", "Coraline", "Back to the Future", "X-Men" ), nrow = 3, ncol = 3)

movies_matrix[c(1,2),]
##      [,1]          [,2]                      [,3]                
## [1,] "Halloween"   "The Abyss"               "Coraline"          
## [2,] "The Goonies" "Nightmare on Elm Street" "Back to the Future"

Access More Than One Column

More than one column can be accessed if you use the c() function:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss", "Nightmare on Elm Street", "Friday the 13th", "Coraline", "Back to the Future", "X-Men" ), nrow = 3, ncol = 3)

movies_matrix[, c(1,2)]
##      [,1]           [,2]                     
## [1,] "Halloween"    "The Abyss"              
## [2,] "The Goonies"  "Nightmare on Elm Street"
## [3,] "Total Recall" "Friday the 13th"

Add Rows and Columns

Use the cbind() function to add additional columns in a Matrix:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss", "Nightmare on Elm Street", "Friday the 13th", "Coraline", "Back to the Future", "X-Men" ), nrow = 3, ncol = 3)

new_movie_matrix <- cbind(movies_matrix, c("Existenz", "12 Monkeys", "Scanners"))

# Print the new matrix
new_movie_matrix
##      [,1]           [,2]                      [,3]                 [,4]        
## [1,] "Halloween"    "The Abyss"               "Coraline"           "Existenz"  
## [2,] "The Goonies"  "Nightmare on Elm Street" "Back to the Future" "12 Monkeys"
## [3,] "Total Recall" "Friday the 13th"         "X-Men"              "Scanners"

Note: The cells in the new column must be of the same length as the existing matrix.

Use the rbind() function to add additional rows in a Matrix:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss", "Nightmare on Elm Street", "Friday the 13th", "Coraline", "Back to the Future", "X-Men" ), nrow = 3, ncol = 3)

new_movie_matrix <- rbind(movies_matrix, c("Existenz", "12 Monkeys", "Scanners"))

# Print the new matrix
new_movie_matrix
##      [,1]           [,2]                      [,3]                
## [1,] "Halloween"    "The Abyss"               "Coraline"          
## [2,] "The Goonies"  "Nightmare on Elm Street" "Back to the Future"
## [3,] "Total Recall" "Friday the 13th"         "X-Men"             
## [4,] "Existenz"     "12 Monkeys"              "Scanners"

Note: The cells in the new row must be of the same length as the existing matrix.

Remove Rows and Columns

Use the c() function to remove rows and columns in a Matrix:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss", "Nightmare on Elm Street", "Friday the 13th"), nrow = 3, ncol =2)

#Remove the first row and the first column
movies_matrix <- movies_matrix[-c(1), -c(1)]

movies_matrix
## [1] "Nightmare on Elm Street" "Friday the 13th"

Check if an Item Exists

To find out if a specified item is present in a matrix, use the %in% operator:

# Check if "Halloween" is present in the matrix:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss"), nrow = 2, ncol = 2)

"Halloween" %in% movies_matrix
## [1] TRUE

Number of Rows and Columns

Use the dim() function to find the number of rows and columns in a Matrix:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss"), nrow = 2, ncol = 2)

dim(movies_matrix)
## [1] 2 2

Matrix Length

Use the length() function to find the dimension of a Matrix:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss"), nrow = 2, ncol = 2)

length(movies_matrix)
## [1] 4

Total cells in the matrix is the number of rows multiplied by number of columns.

In the example above: Dimension = 2*2 = 4.

Loop Through a Matrix

You can loop through a Matrix using a for loop. The loop will start at the first row, moving right:

# Loop through the matrix items and print them:

movies_matrix <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss"), nrow = 2, ncol = 2)

for (rows in 1:nrow(movies_matrix)) {
  for (columns in 1:ncol(movies_matrix)) {
    print(movies_matrix[rows, columns])
  }
}
## [1] "Halloween"
## [1] "Total Recall"
## [1] "The Goonies"
## [1] "The Abyss"

Combine two Matrices

Again, you can use the rbind() or cbind() function to combine two or more matrices together:

# Combine matrices
Matrix1 <- matrix(c("Halloween", "The Goonies", "Total Recall", "The Abyss"), nrow = 2, ncol = 2)
Matrix2 <- matrix(c("Nightmare on Elm Street", "Friday the 13th", "Coraline", "Back to the Future"), nrow = 2, ncol = 2)

# Adding it as a rows
Matrix_Combined <- rbind(Matrix1, Matrix2)
Matrix_Combined
##      [,1]                      [,2]                
## [1,] "Halloween"               "Total Recall"      
## [2,] "The Goonies"             "The Abyss"         
## [3,] "Nightmare on Elm Street" "Coraline"          
## [4,] "Friday the 13th"         "Back to the Future"
# Adding it as a columns
Matrix_Combined <- cbind(Matrix1, Matrix2)
Matrix_Combined
##      [,1]          [,2]           [,3]                     
## [1,] "Halloween"   "Total Recall" "Nightmare on Elm Street"
## [2,] "The Goonies" "The Abyss"    "Friday the 13th"        
##      [,4]                
## [1,] "Coraline"          
## [2,] "Back to the Future"

Arrays

Compared to matrices, arrays can have more than two dimensions.

We can use the array() function to create an array, and the dim parameter to specify the dimensions:

# An array with one dimension with values ranging from 1 to 24
my_array <- c(1:48)
my_array
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
## [26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
# An array with more than one dimension
multi_array <- array(my_array, dim = c(4, 3, 2))
multi_array
## , , 1
## 
##      [,1] [,2] [,3]
## [1,]    1    5    9
## [2,]    2    6   10
## [3,]    3    7   11
## [4,]    4    8   12
## 
## , , 2
## 
##      [,1] [,2] [,3]
## [1,]   13   17   21
## [2,]   14   18   22
## [3,]   15   19   23
## [4,]   16   20   24

Example Explained

In the example above we create an array with the values 1 to 48.

How does dim=c(4,3,2) work?

The first and second number in the bracket specifies the amount of rows and columns.

The last number in the bracket specifies how many dimensions we want.

Note: Arrays can only have one data type.

Access Array Items

You can access the array elements by referring to the index position. You can use the [] brackets to access the desired elements from an array:

my_array <- c(1:48)
multi_array <- array(my_array, dim = c(4, 3, 2))

multi_array[2, 3, 2]
## [1] 22

The syntax is as follow: array[row position, column position, matrix level]

You can also access the whole row or column from a matrix in an array, by using the c() function:

my_array <- c(1:48)

# Access all the items from the first row from matrix one
multi_array <- array(my_array, dim = c(4, 3, 2))
multi_array[c(1),,1]
## [1] 1 5 9
# Access all the items from the first column from matrix one
multi_array <- array(my_array, dim = c(4, 3, 2))
multi_array[,c(1),1]
## [1] 1 2 3 4

A comma (,) before c() means that we want to access the column.

A comma (,) after c() means that we want to access the row.

Check if an Item Exists

To find out if a specified item is present in an array, use the %in% operator:

# Check if the value "2" is present in the array:

my_array <- c(1:48)
multi_array <- array(my_array, dim = c(4, 3, 2))

2 %in% multi_array
## [1] TRUE

Amount of Rows and Columns

Use the dim() function to find the amount of rows and columns in an array:

my_array <- c(1:48)
multi_array <- array(my_array, dim = c(4, 3, 2))

dim(multi_array)
## [1] 4 3 2

Array Length

Use the length() function to find the dimension of an array:

my_array <- c(1:48)
multi_array <- array(my_array, dim = c(4, 3, 2))

length(multi_array)
## [1] 24

Loop Through an Array

You can loop through the array items by using a for loop:

my_array <- c(1:48)
multi_array <- array(my_array, dim = c(4, 3, 2))

for(x in multi_array){
  print(x)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
## [1] 11
## [1] 12
## [1] 13
## [1] 14
## [1] 15
## [1] 16
## [1] 17
## [1] 18
## [1] 19
## [1] 20
## [1] 21
## [1] 22
## [1] 23
## [1] 24

Data Frames

Data Frames are data displayed in a format as a table.

Data Frames can have different types of data inside it. While the first column can be character, the second and third can be numeric or logical. However, each column should have the same type of data.

Use the data.frame() function to create a data frame:

# Create a data frame
df <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)
# Print the data frame
df

Summarize the Data

Use the summary() function to summarize the data from a Data Frame:

df <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

df
summary(df)
##   franchise             order         duration    
##  Length:4           Min.   :1.00   Min.   :109.0  
##  Class :character   1st Qu.:1.75   1st Qu.:114.2  
##  Mode  :character   Median :2.50   Median :116.5  
##                     Mean   :2.50   Mean   :144.8  
##                     3rd Qu.:3.25   3rd Qu.:147.0  
##                     Max.   :4.00   Max.   :237.0

You will learn more about the summary() function in the statistical part of the R tutorial.

#Access Items

We can use single brackets [ ], double brackets [[ ]] or $ to access columns from a data frame:

df <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

df[1]
df[["franchise"]]
## [1] "Alien"               "Aliens"              "Alien 3"            
## [4] "Alien: Resurrection"
df$franchise
## [1] "Alien"               "Aliens"              "Alien 3"            
## [4] "Alien: Resurrection"

Add Rows

Use the rbind() function to add new rows in a Data Frame:

df <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

# Add a new row
New_row_df <- rbind(df, c("AvP", 5, 101))

# Print the new row
New_row_df

Add Columns

Use the cbind() function to add new columns in a Data Frame:

df <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

# Add a new column
New_col_df <- cbind(df, years = c(1979, 1986, 1992, 1997))

# Print the new column
New_col_df

Remove Rows and Columns

Use the c() function to remove rows and columns in a Data Frame:

df <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

# Remove the first row and column
df_New <- df[-c(1), -c(1)]

# Print the new data frame
df_New

Amount of Rows and Columns

Use the dim() function to find the amount of rows and columns in a Data Frame:

df <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

dim(df)
## [1] 4 3

You can also use the ncol() function to find the number of columns and nrow() to find the number of rows:

df <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

ncol(df)
## [1] 3
nrow(df)
## [1] 4

Data Frame Length

Use the length() function to find the number of columns in a Data Frame (similar to ncol()):

df <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

length(df)
## [1] 3

Combining Data Frames

Use the rbind() function to combine two or more data frames in R vertically:

df1 <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

df2 <- data.frame (
  franchise = c("AvP", "AvP: Requiem"),
  order = c(5,6),
  duration = c(101, 94)
)

New_df <- rbind(df1, df2)
New_df

And use the cbind() function to combine two or more data frames in R horizontally:

df3 <- data.frame (
  franchise = c("Alien", "Aliens", "Alien 3", "Alien: Resurrection"),
  order = c(1,2,3,4),
  duration = c(117, 237, 116, 109)
)

df4 <- data.frame (
  release_year = c(1979, 1986, 1992, 1997),
  director = c("Ridley Scott", "James Cameron", "David Fincher", "Jean-Pierre Jeunet")
)

New_df1 <- cbind(df3, df4)
New_df1

Factors

Factors are used to categorize data. Examples of factors are:

Demography: Male/Female Music: Metal, Hip Hop, Classic, Jazz, Alternative, Reggae, IDM Movies: Evil Dead, Hellraiser, Candyman

To create a factor, use the factor() function and add a vector as argument:

# Create a factor
music_genre <- factor(c("Jazz", "Alternative", "Classic", "Classic", "Hip Hop", "Jazz", "Alternative", "Jazz", "Metal"))

# Print the factor
music_genre
## [1] Jazz        Alternative Classic     Classic     Hip Hop     Jazz       
## [7] Alternative Jazz        Metal      
## Levels: Alternative Classic Hip Hop Jazz Metal

Levels: Metal, Hip Hop, Classic, Jazz, Alternative, Reggae, IDM

You can see from the example above that that the factor has 7 levels (categories): Metal, Hip Hop, Classic, Jazz, Alternative, Reggae, IDM.

To only print the levels, use the levels() function:

music_genre <- factor(c("Jazz", "Alternative", "Classic", "Classic", "Hip Hop", "Jazz", "Alternative", "Jazz", "Metal"))

levels(music_genre)
## [1] "Alternative" "Classic"     "Hip Hop"     "Jazz"        "Metal"

You can also set the levels, by adding the levels argument inside the factor() function:

music_genre <- factor(c("Jazz", "Alternative", "Classic", "Classic", "Hip Hop", "Jazz", "Alternative", "Jazz", "Metal"), levels = c("Jazz", "Alternative", "Classic",  "Hip Hop",  "Metal", "Hard Core", "Rap", "Country"))

levels(music_genre)
## [1] "Jazz"        "Alternative" "Classic"     "Hip Hop"     "Metal"      
## [6] "Hard Core"   "Rap"         "Country"

Factor Length

Use the length() function to find out how many items there are in the factor:

music_genre <- factor(c("Jazz", "Alternative", "Classic", "Classic", "Hip Hop", "Jazz", "Alternative", "Jazz", "Metal"))

length(music_genre)
## [1] 9

Access Factors

To access the items in a factor, refer to the index number, using [] brackets:

Access the third item:

music_genre <- factor(c("Jazz", "Alternative", "Classic", "Classic", "Hip Hop", "Jazz", "Alternative", "Jazz", "Metal"))

music_genre[3]
## [1] Classic
## Levels: Alternative Classic Hip Hop Jazz Metal

Change Item Value

To change the value of a specific item, refer to the index number:

# Change the value of the third item:

music_genre <- factor(c("Jazz", "Alternative", "Classic", "Classic", "Hip Hop", "Jazz", "Alternative", "Jazz", "Metal"))

music_genre[3] <- "Slap Funk"
## Warning in `[<-.factor`(`*tmp*`, 3, value = "Slap Funk"): invalid factor level,
## NA generated
music_genre[3]
## [1] <NA>
## Levels: Alternative Classic Hip Hop Jazz Metal

Note that you cannot change the value of a specific item if it is not already specified in the factor. The following example will produce an error:

Example Trying to change the value of the third item (“Classic”) to an item that does not exist/not predefined (“Funk”):

music_genre <- factor(c("Jazz", "Rock", "Classic", "Classic", "Pop", "Jazz", "Rock", "Jazz"), levels = c("Classic", "Jazz", "Pop", "Rock", "Funk"))

music_genre[3] <- "Funk"

music_genre[3]
## [1] Funk
## Levels: Classic Jazz Pop Rock Funk