Skip to main content
eLearner.app

R Course

Cheatsheet

A quick reference — the essential R syntax on a single page. Press Ctrl/Cmd + P to print it.

R · Cheatsheet — eLearner.app

Variables and Vectors

  • Variable Assignment

    x <- 10
    y <- 20
    total <- x + y

    Use the <- operator to assign a value to a variable in R.

  • Creating Vectors

    numbers <- c(5, 10, 15, 20)
    names <- c("Alice", "Bob")
    logical_values <- c(TRUE, FALSE, TRUE)

    The c() function concatenates elements into a vector of the same type.

  • Vectorized Operations

    v1 <- c(1, 2, 3)
    doubled <- v1 * 2         # c(2, 4, 6)
    
    v2 <- c(10, 20, 30)
    sum_vec <- v1 + v2        # c(11, 22, 33)

    Mathematical operations applied to a vector are executed element-by-element.

Matrices and Data Frames

  • Matrix Creation and Access

    mat <- matrix(1:6, nrow = 2, ncol = 3)
    
    val <- mat[1, 3]          # Element (row 1, column 3)
    row1 <- mat[1, ]          # Entire first row
    col2 <- mat[, 2]          # Entire second column

    Matrices are two-dimensional and contain elements of the same type.

  • Data Frame Creation and Filtering

    df <- data.frame(
      name = c("Alice", "Bob"),
      grade = c(28, 24)
    )
    
    # Extract a column
    grades <- df$grade
    
    # Filter rows
    good_students <- df[df$grade >= 26, ]

    Data Frames can contain columns of different types and represent tabular data.

Control Flow

  • IF-ELSE Conditionals

    score <- 75
    
    if (score >= 60) {
      status <- "Pass"
    } else {
      status <- "Fail"
    }

    Use round parentheses for the condition and curly braces for blocks.

  • FOR Loop

    for (i in 1:5) {
      print(i)
    }
    
    v <- c(2, 4, 6)
    for (val in v) {
      print(val * 2)
    }

    Iterates over elements in a sequence or a vector using the 'in' keyword.

Functions and Data Analysis

  • Defining Functions

    calculate_tax <- function(amount, rate = 0.22) {
      result <- amount * rate
      return(result)
    }

    Functions can specify default parameters (like rate = 0.22) and use return() to yield a value.

  • Basic Statistics and NA values

    temperatures <- c(22, 25, NA, 21)
    
    # Calculate mean ignoring NA values
    mean_temp <- mean(temperatures, na.rm = TRUE)
    
    # Standard Deviation
    sd_temp <- sd(temperatures, na.rm = TRUE)
    
    # Complete statistical summary
    summary_stats <- summary(temperatures)

    The na.rm = TRUE argument specifies to remove missing values (NA) before running calculations.

eLearner.app · R Course · cheatsheet generated from lesson content.