Vector is a combination of different values (numeric, character, logical, etc depending on the input data types) in the same object/variable.
In the following case study, the reader has the appropriate input data types, namely numeric vectors, character vectors, logical vectors, and so on.
Vector in RStudio can made using c() function (concatenate). Here’s the example:
# Create Numeric Vector
a <- c(9, 10, 2 , 7)
# Print the vector
a
## [1] 9 10 2 7
# Create Character Vector
b <- c("Cockroach", "Ant", "Mosquito", "Bee")
# Print the vector
b
## [1] "Cockroach" "Ant" "Mosquito" "Bee"
In addition to entering values for the vectors, we can also use the names() function to provide a value name for each vector.
# Creates a vector with the number of fruits purchased
fruitValues <- c(10, 15, 20, 8)
names(fruitValues) <- c("Orange", "Watermelon", "Kiwi", "Guava")
# Or we can type like this
fruitValues <- c(Orange=10, Watermelon=15, Kiwi=20, Guava=8)
# Print
fruitValues
## Orange Watermelon Kiwi Guava
## 10 15 20 8
Vectors can contain only one data type. Vectors can contain only numeric data types, only characters, and so on.
To find the length of a vector, we can use length() function. Here’s the example:
# Find the length of fruitValues
length(fruitValues)
## [1] 4