In this section, we will dive into the fundamental operations in R, including variables and data types, arithmetic operations, and working with vectors and matrices.
In R, variables are used to store data. Before we can perform operations on data, we need to understand different data types. Here are some common data types in R:
Let’s see some examples:
# Numeric
num_var <- 3.14
# Integer
int_var <- 42L
# Character
char_var <- "Hello, R!"
# Logical
logical_var <- TRUE
R allows you to perform a wide range of arithmetic operations on numeric data. Here are some basic operations:
# Examples of arithmetic operations
x <- 10
y <- 5
addition_result <- x + y
addition_result
## [1] 15
subtraction_result <- x - y
subtraction_result
## [1] 5
multiplication_result <- x * y
multiplication_result
## [1] 50
division_result <- x / y
division_result
## [1] 2
exponentiation_result <- x ^ y
exponentiation_result
## [1] 100000
modulo_result <- x %% y
modulo_result
## [1] 0
Vectors and matrices are fundamental data structures in R that allow you to work with collections of data efficiently.
A vector is a one-dimensional array that can hold elements of the same data type. You can create vectors using the c() function:
# Creating a numeric vector
numeric_vector <- c(1, 2, 3, 4, 5)
# Creating a character vector
char_vector <- c("apple", "banana", "cherry")
A matrix is a two-dimensional array that can hold elements of the same data type. You can create matrices using the matrix() function:
# Creating a matrix
matrix_data <- matrix(1:6, nrow = 2, ncol = 3)
matrix_data
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
These are the basics of working with variables, data types, arithmetic operations, vectors, and matrices in R. In the next sections, we will explore more advanced topics and practical examples.
Feel free to practice these concepts in your R environment to solidify your understanding.
Free Lessons: