Saturday 10 February 2024

Vectors in R Programming and types of vectors


Vectors in R Programming and types of vectors

What are Vectors?

  • Fundamental Data Structure: Vectors in R are the most basic and fundamental data structure. They are one-dimensional arrays that store elements of a single data type.

  • Homogeneous: All the elements within a vector must be of the same type (e.g., all numbers, all characters, etc.).

Vectors in R Programming and types of vectors

Types of Vectors

R supports six atomic vector types:

  1. Numeric: Stores numbers (integers or doubles, i.e., decimals).

  • Example: my_numeric <- c(1, 5, 2.7, 10)

  1. Integer: Stores whole numbers only.

  • Example: my_integer <- c(2L, 6L, 15L) (the 'L' signifies integer)

  1. Logical: Stores Boolean values (TRUE or FALSE).

  • Example: my_logical <- c(TRUE, FALSE, TRUE)

  1. Character: Stores text or strings.

  • Example: my_character <- c("hello", "world", "data")

  1. Complex: Stores complex numbers (numbers with real and imaginary parts).

  • Example: my_complex <- c(2+5i, 3-1i)

  1. Raw: Stores raw bytes of data (this type is less commonly used directly).

Creating Vectors

The primary way to create vectors in R is using the c() function (short for "combine"):

Code snippet

# Create a numeric vector
numbers <- c(5, 2, 8.3, 1)

# Create a character vector
greetings <- c("hello", "good morning")

Operations on Vectors

  • Accessing Elements: Access specific elements using square brackets [] and their index (position). Indexing starts from 1.
    Code snippet
    numbers[2]  # Accesses the second element

  • Arithmetic Operations: Perform element-wise addition, subtraction, multiplication, division, etc.
    Code snippet
    numbers * 2   # Multiply each element by 2

  • Logical Comparisons: Perform element-wise comparisons (<, >, ==, etc.).
    Code snippet
    numbers > 4   # Check which elements are greater than 4

  • Functions: Apply various built-in functions to vectors.
    Code snippet
    length(numbers)  # Find the length (number of elements)
    sum(numbers)     # Calculate the sum
    sort(numbers)    # Sort in ascending order

Key Points

  • Vectors are an essential building block in R, used extensively in data analysis and manipulation.

  • Understanding different vector types ensures you store and work with your data correctly.

  • R provides a rich set of functions and operations for working with vectors.

1. Deleting an Entire Vector

To completely remove a vector from your R workspace, use the rm() function:

Code snippet

my_vector <- c(10, 20, 30)  # Create a vector

rm(my_vector)  # Remove the vector

Vectors in R Programming and types of vectors

No comments:

Post a Comment

Note: only a member of this blog may post a comment.