...

Artificial Intelligence - R Programming Advanced

Back to Course

Lesson Description


Lession - #864 R Vectors


Vectors

A vector is simply 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.
In the example below, we create a vector variable called fruits, that combine strings:
Example

# Vector of strings
fruits <- c("banana", "apple", "orange">


# Print fruits
fruits
In this example, we create a vector that combines numerical values:
Example

# Vector of numerical values
numbers <- c(1, 2, 3>


# Print numbers
numbers
To create a vector with numerical values in a sequence, use the
:
operator:
Example

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

numbers
Vector Length

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

fruits <- c("banana", "apple", "orange">


length(fruits>


Sort a Vector

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

fruits <- c("banana", "apple", "orange", "mango", "lemon">

numbers <- c(13, 3, 5, 7, 20, 2>


sort(fruits>
  # Sort a string
sort(numbers>
# Sort numbers

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:
Example

fruits <- c("banana", "apple", "orange">


# Access the first item (banana>

fruits[1]
You can also access multiple elements by referring to different index positions with the
c(>
function:
Example

fruits <- c("banana", "apple", "orange", "mango", "lemon">


# Access the first and third item (banana and orange>

fruits[c(1, 3>
]
You can also use negative index numbers to access all items except the ones specified:
Example

fruits <- c("banana", "apple", "orange", "mango", "lemon">


# Access all items except for the first item
fruits[c(-1>
]

Change an Item

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

fruits <- c("banana", "apple", "orange", "mango", "lemon">


# Change "banana" to "pear"
fruits[1] <- "pear"

# Print fruits
fruits

Repeat Vectors

To repeat vectors, use the
rep(>
function:
Example

Repeat each value:
repeat_each <- rep(c(1,2,3>
, each = 3>


repeat_each

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:
Example

numbers <- 1:10

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

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


numbers