In R, an object is used to store various types of data, and the objects can be as simple as a single value (number or char) or as complex as a list of multiple elements. The object is a data structure.
Types of Objects in R
Vectors: The most basic type of object in R. A vector is a one-dimensional array that can contain character, numeric, logical, and complex data, but all elements in a vector must be of the same type.
Example:
Numeric vector: x<- c(5.6, 24.3, 73.4)
Character vector: y<- c("rock", "paper", "scissors")
Logical vector: z <- c(TRUE, FALSE, TRUE)
Lists: Lists are objects that can contain elements of different types, including other lists too. They are used for grouping related data.
Example:
new_list <- list(name = "Rahul", age = 32, scores = c(80, 82, 83))
Matrices: Matrices are two-dimensional arrays that can only contain elements of the same type. They are created by using this function matrix().
Example:
new_matrix <- matrix(1:9, nrow = 3, ncol = 3)
Arrays: Arrays are an n-dimensional collection of data elements. They can contain elements of the same type. They are created by using this function array().
Example:
new_array <- array(1:12, dim = c(3, 4))
Data Frames: Data frames is a table-like structure that can hold different types of variables where each column can be of a different type. They are created by using this function data.frame().
Example:
new_data_frame <- data.frame(name = c("James", "Bond"), age = c(26, 38))
Factors: Factors are used to represent categorical data and they can be ordered or unordered. They are particularly useful in statistical modeling.
Example:
new_factor <- factor(c("male", "female", "female", "male"))
Attributes of Objects
Each object in R can have associated attributes, which provide more information about the object. Some of the common attributes are:
Class: Defines the type of the object (e.g., "data.frame", "matrix").
Dimensions: For matrices and arrays, this defines the number of rows and columns.
Names: Assigns names to the elements in a list or data frame.
Creating and Manipulating Objects
Objects in R are created using assignment operators (like <-), and their properties can be manipulated using various functions. For example, you can check the class of an object using class() and access its attributes using attributes().
Example of Creating and Checking an Object
# Create a vector
new_vector <- c(1, 2, 3)
# Check the class of the vector
class(new_vector) # Output: "numeric"
# Create a data frame
new_df <- data.frame(Name = c("James", "Bond"), Age = c(26, 38))
# Check attributes of the data frame
attributes(new_df)
Intellipaat has one of the best R Programming Tutorials where you can learn in-depth about R.
You must also watch this Intellipaat YouTube tutorial to become proficient in R