# Creating a numeric vector
sales_vector <- c(120, 150, 90, 100, 130, 170, 200)
sales_vector[1] 120 150 90 100 130 170 200
R provides several data structures that are used to store, manage, and manipulate data efficiently. Each structure has its specific use case and characteristics:
Choosing the appropriate data structure is crucial for effective analysis, as each structure is suited for different types of operations and datasets.
You can create a vector using the c() function, which stands for “combine” or “concatenate.” This function allows you to combine multiple elements into a single vector.
# Creating a numeric vector
sales_vector <- c(120, 150, 90, 100, 130, 170, 200)
sales_vector[1] 120 150 90 100 130 170 200
c() function combines the sales figures into a single vector called sales_vector.# Creating a character vector
product_vector <- c("Product A", "Product B", "Product C", "Product D")
product_vector[1] "Product A" "Product B" "Product C" "Product D"
c() function to combine the names into a single character vector.You can access individual elements in a vector using indexing. R indexing starts at 1, meaning the first element of the vector is accessed with vector_name[1].
# Accessing the first element of the sales vector
sales_vector[1] # Returns 120[1] 120
sales_vector, which is the value 120.You can access multiple elements of a vector using a range of indices.
# Accessing the first three elements of the sales vector
sales_vector[1:3] # Returns 120, 150, and 90[1] 120 150 90
1:3 retrieves the first three elements of the sales_vector, returning the sales figures 120, 150, and 90.You can modify specific elements of a vector by assigning new values to a specific index.
# Modifying the second element of the sales vector
sales_vector[2] <- 160
sales_vector[1] 120 160 90 100 130 170 200
sales_vector from 150 to 160.# Creating a numeric matrix
sales_matrix <- matrix(c(120, 150, 90, 100, 130, 170, 200, 210, 180),
nrow = 3,
ncol = 3,
byrow = TRUE)
sales_matrix [,1] [,2] [,3]
[1,] 120 150 90
[2,] 100 130 170
[3,] 200 210 180
# Creating a data frame
sales_data <- data.frame(
Product = c("A", "B", "C"),
Sales_Q1 = c(120, 150, 90),
Sales_Q2 = c(170, 200, 140)
)
sales_data Product Sales_Q1 Sales_Q2
1 A 120 170
2 B 150 200
3 C 90 140
A, B, and C) across two quarters (Q1 and Q2).# Creating a list
sales_list <- list(
Products = c("A", "B", "C"),
Sales = sales_vector,
Sales_Matrix = sales_matrix
)
sales_list$Products
[1] "A" "B" "C"
$Sales
[1] 120 160 90 100 130 170 200
$Sales_Matrix
[,1] [,2] [,3]
[1,] 120 150 90
[2,] 100 130 170
[3,] 200 210 180
# Creating a factor
satisfaction <- factor(c("High", "Medium", "Low", "Medium", "High"))
satisfaction[1] High Medium Low Medium High
Levels: High Low Medium