Dot Product of Vectors in detail
Vectors are the fundamental data types in R. Any object created is stored as a vector by default. A vector is essentially a sequence of homogeneous data elements, similar to arrays in other programming languages. When a vector contains mixed data types, R automatically converts the elements to the type with the highest precedence.
Numerous operations can be performed on vectors in R, such as creation, access, modification, deletion, arithmetic operations, and sorting.
What is an Append Operation in R?
A vector in R is a basic object that contains sequences of elements of the same type. It can hold values such as integers, characters, logicals, doubles, etc. You can append new values to an existing vector using three primary methods:
- Using the
c()function - Using the
append()function - Using indexing
1. Append Operation Using c() Function
The c() function is a generic function that combines multiple objects into a single vector or list.
Syntax:
c(...)
Parameters:
...: The objects or values to be concatenated.
To explore additional options, run:
help("c")
Example 1: Basic Append with c()
# Create vectors
nums <- 10:14
extra_nums <- 15:18
# Append using c()
result <- c(nums, extra_nums)
# Print result
print(result)
Output:
[1] 10 11 12 13 14 15 16 17 18
Example 2: Append with Mixed Types
# Create vectors
nums <- 1:4
chars <- c("x", "y", "z")
# Append using c()
combined <- c(nums, chars)
# Print result
print(combined)
# Check types
print(typeof(combined))
print(typeof(nums))
print(typeof(chars))
Output:
[1] "1" "2" "3" "4" "x" "y" "z"
[1] "character"
[1] "integer"
[1] "character"
2. Append Operation Using append() Function
The append() function is specifically designed to merge vectors or add elements to a vector.
Syntax:
append(x, values)
Parameters:
x: The vector to which elements are appended.values: The values to append to the vector.
Example 3: Append with append() Function
# Create a vector
vec <- c(20, 30, 40)
# Append values
vec <- append(vec, c(50, 60))
# Print result
print(vec)
Output:
[1] 20 30 40 50 60
Example 4: Append Mixed Types with append()
# Create vectors
nums <- c(1, 2, 3)
letters <- c("a", "b", "c")
# Append characters to numeric vector
combined <- append(nums, letters)
# Print result
print(combined)
Output:
[1] "1" "2" "3" "a" "b" "c"
3. Append Operation Using Indexing
You can also add elements to a vector by directly assigning values to positions beyond its current length.
Example 5: Append Using Indexing
# Create a vector
my_vector <- c(5, 10, 15)
# Append values using indexing
my_vector[4] <- 20
my_vector[5] <- 25
# Print result
print(my_vector)
Output:
[1] 5 10 15 20 25
Leave a Reply