# Assign values to variables
x <- 10
y <- 5
# Print the variables
x
yBase R Crash Course: Core Concepts
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^y3. Data Types
R has several basic data types, which are essential to understand for any operation.
Numeric Data Type
num <- 42.5 # Decimal numbers
numInteger Data Type
int <- 10L # Add "L" to specify an integer
intCharacter Data Type
char <- "Hello, World!"
charLogical Data Type
logi <- TRUE
logiChecking Data Type
You can check the type of any variable using the class() function.
class(num) # NumericType 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) # IntegerType 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 possible4. 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)]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)- 11
- 12
- 13
- 14
- 15
- 5
- 7
- 9
- TRUE
- FALSE
- 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)- 'apple'
- 'banana'
- 'cherry'
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
-
- 90
- 85
- 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- 90
- 85
- 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| 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]- 1
- 4
- 7
- 4
- 5
- 6
Matrix Operations
# Transpose the matrix
t(mat)
# Matrix multiplication
mat %*% t(mat)
# Element-wise multiplication
mat * mat| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
| 66 | 78 | 90 |
| 78 | 93 | 108 |
| 90 | 108 | 126 |
| 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| 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]- 'Alice'
- 'Bob'
- 'Charlie'
| Name | Age | Score | |
|---|---|---|---|
| <chr> | <dbl> | <dbl> | |
| 2 | Bob | 22 | 76 |
Adding New Columns
# Add a new column to the data frame
df$City <- c("New York", "San Francisco", "Chicago")
# View updated data frame
df| 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)| 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)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()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.