R Data structres

R is known for its versatility in handling various data structures. Some of the most commonly used data structures in R programming are:

Vector:

  • A vector is a one-dimensional array that can hold elements of the same data type.
  • You can create a vector using the c() function.
  • Example: my_vector <- c(1, 2, 3, 4, 5)

Matrix:

  • A matrix is a two-dimensional data structure with rows and columns.
  • You can create a matrix using the matrix() function.
  • Example: my_matrix <- matrix(1:9, nrow = 3, ncol = 3)

List:

  • A list is a collection of different data types and can include vectors, matrices, data frames, and other lists.
  • You can create a list using the list() function.
  • Example: my_list <- list(name = “John”, age = 30, scores = c(85, 90, 78))

Data Frame:

  • A data frame is a two-dimensional table-like structure where each column can be of a different data type.
  • Data frames are used for storing and manipulating datasets.
  • You can create a data frame using the data.frame() function.
  • Example:

my_data <- data.frame(

  Name = c(“Alice”, “Bob”, “Charlie”),

  Age = c(25, 30, 22),

  Score = c(95, 88, 72)

)

Factor:

  • A factor is a categorical variable that can take on a limited, fixed number of values, known as levels.
  • Factors are useful for representing and working with categorical data.
  • You can create a factor using the factor() function.
  • Example: my_factor <- factor(c(“Low”, “Medium”, “High”), levels = c(“Low”, “Medium”, “High”))

Array:

  • An array is a multi-dimensional data structure that can have more than two dimensions.
  • You can create an array using the array() function.
  • Example: my_array <- array(1:12, dim = c(2, 3, 2))

Table:

  • A table is a one-dimensional array with named elements and is similar to a list.
  • You can create a table using the table() function.
  • Example: my_table <- table(apples = c(1, 2, 1, 3, 2, 2))

These are some of the fundamental data structures in R, and each has its own specific use cases and functions for manipulation and analysis. Depending on the type of data you’re working with, you’ll choose the appropriate data structure to best represent and process your data.

Leave a Comment

Your email address will not be published. Required fields are marked *