Base R Crash Course: Core Concepts

# Assign values to variables
x <- 10
y <- 5

# Print the variables
x
y
10
5

Simple Arithmetic Operations

# Addition
sum <- x + y

# Subtraction
difference <- x - y

# Multiplication
product <- x * y

# Division
quotient <- x / y

# Modulus (remainder)
remainder <- x %% y

# Exponentiation
power <- x^y

3. Data Types

R has several basic data types, which are essential to understand for any operation.

Numeric Data Type

num <- 42.5  # Decimal numbers
num
42.5

Integer Data Type

int <- 10L  # Add "L" to specify an integer
int
10

Character Data Type

char <- "Hello, World!"
char
'Hello, World!'

Logical Data Type

logi <- TRUE
logi
TRUE

Checking Data Type

You can check the type of any variable using the class() function.

class(num)   # Numeric
'numeric'

Type Checking Continued

You can check the type of any variable using the class() and typeof() functions:

class(num)   # Numeric
class(char)  # Character
class(logi)  # Logical

typeof(int)  # Integer
'numeric'
'character'
'logical'
'integer'

Type Conversion

Converting between types is often necessary when working with different data.

# Convert numeric to integer
num_to_int <- as.integer(num)

# Convert integer to numeric
int_to_num <- as.numeric(int)

# Convert numeric to character
num_to_char <- as.character(num)

# Convert character to numeric
char_to_num <- as.numeric("123")  # Works only if conversion is possible

4. Vectors

Vectors are one of the most basic data structures in R and represent a sequence of elements of the same type.

Creating Vectors

# Numeric vector
num_vec <- c(1, 2, 3, 4, 5)

# Character vector
char_vec <- c("apple", "banana", "cherry")

# Logical vector
logi_vec <- c(TRUE, FALSE, TRUE)

Accessing Vector Elements

You can access vector elements using indexing. In R, indices start at 1.

# Access the 2nd element of num_vec
num_vec[2]

# Access the last element of char_vec
char_vec[length(char_vec)]
2
'cherry'

Vector Operations

Vectors in R are vectorized, meaning you can perform operations element-wise.

# Add a constant to each element
num_vec + 10

# Element-wise addition of two vectors
vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
vec1 + vec2

# Logical operations
logi_vec & c(TRUE, FALSE, FALSE)
  1. 11
  2. 12
  3. 13
  4. 14
  5. 15
  1. 5
  2. 7
  3. 9
  1. TRUE
  2. FALSE
  3. FALSE

Common Vector Functions

# Length of a vector
length(num_vec)

# Sort a vector
sorted_vec <- sort(num_vec)

# Find unique elements
unique(char_vec)

# Calculate sum and mean
sum(num_vec)
mean(num_vec)
5
  1. 'apple'
  2. 'banana'
  3. 'cherry'
15
3

5. Lists

A list is an ordered collection of elements that can contain different types of data (e.g., vectors, matrices, or even other lists).

Creating a List

my_list <- list(name = "John", age = 25, scores = c(90, 85, 88))

# View the list
my_list
$name
'John'
$age
25
$scores
  1. 90
  2. 85
  3. 88

Accessing List Elements

You can access list elements using either the $ operator or square brackets.

# Access 'name' using $
my_list$name

# Access 'age' using square brackets
my_list[["age"]]

# Access the vector 'scores'
my_list$scores
'John'
25
  1. 90
  2. 85
  3. 88

Modifying a List

# Change the 'name'
my_list$name <- "Jane"

# Add a new element
my_list$city <- "New York"

6. Matrices

A matrix is a 2-dimensional data structure where each element must be of the same type (numeric, character, etc.).

Creating a Matrix

# Create a 3x3 matrix
mat <- matrix(1:9, nrow = 3, ncol = 3)

# View the matrix
mat
A matrix: 3 × 3 of type int
1 4 7
2 5 8
3 6 9

Accessing Matrix Elements

You can access matrix elements by specifying their row and column indices.

# Access element in the 2nd row, 3rd column
mat[2, 3]

# Access the entire 1st row
mat[1, ]

# Access the entire 2nd column
mat[, 2]
8
  1. 1
  2. 4
  3. 7
  1. 4
  2. 5
  3. 6

Matrix Operations

# Transpose the matrix
t(mat)

# Matrix multiplication
mat %*% t(mat)

# Element-wise multiplication
mat * mat
A matrix: 3 × 3 of type int
1 2 3
4 5 6
7 8 9
A matrix: 3 × 3 of type dbl
66 78 90
78 93 108
90 108 126
A matrix: 3 × 3 of type int
1 16 49
4 25 64
9 36 81

7. Data Frames

A data frame is a table where each column can have a different data type (e.g., numeric, character, factor). It’s one of the most commonly used data structures in R.

Creating a Data Frame

# Create a data frame
df <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(24, 22, 23),
  Score = c(89, 76, 95)
)

# View the data frame
df
A data.frame: 3 × 3
Name Age Score
<chr> <dbl> <dbl>
Alice 24 89
Bob 22 76
Charlie 23 95

Accessing Data Frame Elements

You can access specific elements, rows, or columns using indexing.

# Access the 'Name' column
df$Name

# Access the 2nd row
df[2, ]

# Access a specific element (3rd row, 2nd column)
df[3, 2]
  1. 'Alice'
  2. 'Bob'
  3. 'Charlie'
A data.frame: 1 × 3
Name Age Score
<chr> <dbl> <dbl>
2 Bob 22 76
23

Adding New Columns

# Add a new column to the data frame
df$City <- c("New York", "San Francisco", "Chicago")

# View updated data frame
df
A data.frame: 3 × 4
Name Age Score City
<chr> <dbl> <dbl> <chr>
Alice 24 89 New York
Bob 22 76 San Francisco
Charlie 23 95 Chicago

Subsetting a Data Frame

You can filter rows based on conditions.

# Subset rows where Age is greater than 22
subset(df, Age > 22)
A data.frame: 2 × 4
Name Age Score City
<chr> <dbl> <dbl> <chr>
1 Alice 24 89 New York
3 Charlie 23 95 Chicago

8. Control Structures

Control structures allow you to control the flow of execution based on conditions or iterations.

If-Else Statement

# Example of if-else
x <- 5
if (x > 0) {
  print("x is positive")
} else {
  print("x is non-positive")
}
[1] "x is positive"

For Loops

# Example of a for loop
for (i in 1:5) {
  print(i)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

While Loop

# Example of a while loop
i <- 1
while (i <= 5) {
  print(i)
  i <- i + 1
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

9. Functions

Functions in R allow you to create reusable blocks of code. You define a function using the function() keyword.

Defining a Function

# Define a function that adds two numbers
add_numbers <- function(a, b) {
  return(a + b)
}

# Call the function
add_numbers(5, 3)
8

Default Arguments

You can provide default values for function arguments.

# Define a function with default arguments
greet <- function(name = "User") {
  paste("Hello,", name)
}

# Call the function with and without arguments
greet("Alice")
greet()
'Hello, Alice'
'Hello, User'

10. Conclusion

This Base R crash course covers the core concepts needed to get started with R, including:

  • Variables and basic data types (numeric, integer, character, logical).
  • Vectors, lists, matrices, and data frames—the primary data structures in R.
  • Control structures such as loops and conditionals to manage the flow of your program.
  • Creating and using functions to make reusable code blocks.

Mastering these concepts will give you a strong foundation to perform more advanced tasks in R, such as data analysis and visualization.

What’s on your mind? Put it in the comments!