Lecture 9

R Basics

Byeong-Hak Choe

SUNY Geneseo

September 16, 2024

R Basics

R Basics

Accessing Subsets of Vectors in R

  • An important aspect of working with R objects is knowing how to “index” them.
    • Indexing enables the filtering of data subsets for further analysis.
  • We focus on two primary types of vector indexing: positional and logical.
  • To access elements in a vector vec, use vec[] with one of these methods:
    1. Single index: vec[n] where n is a positive integer
    2. Vector of indices: vec[c(i, j, k)] where i, j, k are positive integers
    3. Logical condition: vec[condition] where condition is a logical expression

R Basics

Accessing Subsets of Vectors in R

Positional Indexing

  • An index is a positional reference (e.g., 1, 2, 3) used to access individual elements within data structures like a vector.
    • In R, the index is positive integer, starting at 1.
    my_vector <- c(10, 20, 30, 40, 50, 60)
    my_vector[2]
    my_vector[4]
    my_vector[6]

R Basics

Accessing Subsets of Vectors in R

A Vector of Indices

  • Selecting multiple elements by providing a vector of indices
my_vector[ c(3,4,5) ]
my_vector[ 3:5 ]

R Basics

Accessing Subsets of Vectors in R

Logical Indexing

  • Using conditions to filter elements of a vector.
# Filter elements greater than 10
is_greater_than_10 <- my_vector > 10  # Creates logical vector
my_vector[ is_greater_than_10 ] 

R Basics

Tidy data.frame: Variables, Observations, and Values

  • There are three rules which make a data.frame tidy:

    1. Each variable must have its own column.
    2. Each observation must have its own row.
    3. Each value must have its own cell.

:::

–> –> –> –>