Syntax and Data Types in R Programming
1. Vectors
Vectors are the simplest data type in R. They are sequences of elements of the same type.
# Creating a numeric vector
numeric_vector <- c(1, 2, 3, 4, 5)
print(numeric_vector)
# Creating a character vector
character_vector <- c("apple", "banana", "cherry")
print(character_vector)
# Creating a logical vector
logical_vector <- c(TRUE, FALSE, TRUE)
print(logical_vector)
2. Lists
Lists can contain elements of different types, such as numbers, strings, and vectors.
# Creating a list
my_list <- list(
name = "John",
age = 25,
scores = c(90, 85, 88)
)
print(my_list)
# Accessing list elements
print(my_list$name)
print(my_list$scores)
3. Matrices
Matrices are two-dimensional arrays where all elements must be of the same type.
# Creating a matrix
my_matrix <- matrix(
c(1, 2, 3, 4, 5, 6),
nrow = 2,
ncol = 3
)
print(my_matrix)
# Accessing matrix elements
print(my_matrix[1, 2])
4. Data Frames
Data frames are like tables and can hold data of different types in columns.
# Creating a data frame
my_data_frame <- data.frame(
Name = c("Alice", "Bob", "Charlie"),
Age = c(25, 30, 35),
Gender = c("F", "M", "M")
)
print(my_data_frame)
# Accessing data frame elements
print(my_data_frame$Name)
print(my_data_frame[1, ])
5. Factors
Factors are used to represent categorical data and store it as levels.
# Creating a factor
my_factor <- factor(c("small", "large", "medium", "large", "small"))
print(my_factor)
# Displaying the levels
print(levels(my_factor))
Conclusion
This tutorial introduced the basic syntax and data types in R, including vectors, lists, matrices, data frames, and factors. These are foundational for working with data in R programming.