Here, we will discuss vectors in R, how to create vectors, coerce vectors, and operations such as add, subtract, multiply or divide vectors.
This object is the primary building block of other objects in R. A vector contains homogeneous data types and it is 1-dimensional. Its composition can be one of the numeric (or double), integer, character, logical, complex or raw data types.
Create a vector with numeric (or double) elements:
[1] 1 4 9 16 25 36 49 64 81 100
Create a vector with character elements:
[1] "Red" "Blue" "Green"
Create an empty vector:
[1] NA NA NA NA NA
Assign values to (or edit) some index of a vector:
[1] 10 10 10 NA 100
Function | Usage |
length() |
Check or set a vector’s length |
is.vector() |
Check if vector |
typeof() |
Check data type |
is.*type*() |
Check if vector is type |
as.vector() |
Coerce into vector |
as.*type*() |
Coerce vector into type |
type is numeric, integer, character, logical, or complex.
See examples below.
Check the length of a vector:
[1] 5
Set or change the length of a vector:
[1] 1 4 9 16 25
[1] 1 4 9 16 25 NA NA NA NA NA
[1] 1 4 9
Check if an object is a vector:
[1] TRUE
Check the data type or mode of a vector:
[1] "double"
[1] "character"
Check if a vector’s components are of a type/mode:
[1] TRUE
[1] FALSE
[1] TRUE
Coerce an object into a vector:
This example turns a matrix into a vector.
[,1] [,2]
[1,] 1 2
[2,] 4 8
[3,] 16 32
[1] 1 4 16 2 8 32
Coerce a vector’s components into a different type/mode:
[1] "integer"
[1] "character"
Add or subtract vectors of the same lengths:
[1] 1 2 3 4 5
[1] 1 2 3 4 5
[1] 2 4 6 8 10
[1] 0 1 2 3 4
You can also add or subtract vectors of different lengths:
[1] 2 2 2 2 2 2 2 2
[1] 1 100 1000
[1] 0 1
Warning in vec3 + vec4: longer object length is not a multiple of shorter
object length
[1] 3 102 1002 3 102 1002 3 102
[1] 2 1 2 1 2 1 2 1
Multiply or divide vectors of the same lengths:
[1] 6 7 8 9 10
[1] 6 7 8 9 10
[1] 36 49 64 81 100
[1] 0.6 0.7 0.8 0.9 1.0
You can also multiply or divide vectors of different lengths:
[1] 2 2 2 2 2 2 2 2
[1] 1 2 3
[1] 1 2
Warning in vec3 * vec4: longer object length is not a multiple of shorter
object length
[1] 2 4 6 2 4 6 2 4
[1] 2 1 2 1 2 1 2 1
For character vectors, you can use the paste()
or paste0()
(with no spacing) to join
components:
[1] "Red" "Blue" "Green"
[1] "Color" "Color" "Color"
[1] "Red Color" "Blue Color" "Green Color"
[1] "RedColor" "BlueColor" "GreenColor"
[1] "The color Red is a primary color." "The color Blue is a primary color."
[3] "The color Green is a primary color."
The feedback form is a Google form but it does not collect any personal information.
Please click on the link below to go to the Google form.
Thank You!
Go to Feedback Form
Copyright © 2020 - 2024. All Rights Reserved by Stats Codes