Types of Objects in R

R language operates on entities which are known as objects. There are various types of objects in R exists, such as vectors, matrices, factors, lists, data frames, functions, etc. In R, objects are classified into several types based on their structure and content.

Types of Objects in R

Matrices

Arrays or matrices are multi-dimensional generalizations of vectors. Matrices are vectors indexed by two or more indices and displayed specially. Matrices contain rows and columns of homogeneous elements. The class of matrices object is “matrix”. See more about matrices by following the matrices.

Factors

Factors are used to handle categorical data. Factor variables may contain two or more levels, used to define the group or category of the variable. See more about factors in detail by following factors.

Lists

Lists are a general form of vectors in which the various elements need not be of the same type, that is, lists may contain heterogeneous data. Lists are often vectors or lists themselves. Lists are a convenient way to get different results from statistical computation, as lists may contain different types of data objects. See more about lists by following the link Lists.

Data Frame

Data frame objects are similar to matrix object structures. Unlike matrix objects, the data frame objects may contain different types of objects, that is, heterogeneous data. Think of the data frame as “Data Matrices” with one row per observational unit but with (possibly) both numerical and categorical variables. Many experiments are best described by data frames, the treatments are categorical but the response (output) is numeric. For more details about the data frame, follow the link data frame.

Functions

Functions are themselves objects. In R Language, functions can be stored in the project’s workspace. Functions provide a quick, simple, and convenient way to extend the functionality and power of R. See more about functions and customization of functions, see Functions.

Examples of Different Types of Objects in R

# Scalar types
x <- 5        # Numeric (integer)
y <- 3.14159  # Numeric (double)
z <- "Hello"  # Character
b <- TRUE     # Logical

# Vector types
numbers <- c(1, 2, 3, 4)                  # Numeric vector
fruits <- c("apple", "banana", "orange")  # Character vector
bools <- c(TRUE, FALSE, TRUE)             # Logical vector

# Data frame
df <- data.frame(
  name = c("Ali", "Babar", "Usman"),
  age = c(25, 30, 28),
  city = c("Multan", "Lahore", "Karachi")
)

# Matrix
mat <- matrix(1:9, nrow = 3, ncol = 3)

# List
my_list <- list(
  numbers = numbers,
  fruits = fruits,
  df = df
)

# Factor
colors <- factor(c("red", "blue", "green", "red"))
Types of Objects in R Language

https://itfeature.com, https://gmstat.com

Leave a Reply

Discover more from R Language Frequently Asked Questions

Subscribe now to keep reading and get access to the full archive.

Continue reading