Learning R Data Types

Understanding the various data types in R

Atomic Data Types

R has several atomic data types including numeric, character, logical, integer, and complex.

  • Numeric: Used for numeric values.
    x <- 10.5
  • Character: Used for text.
    y <- "hello"
  • Logical: Used for boolean values (TRUE/FALSE).
    z <- TRUE
  • Integer: Used for integer values.
    age <- 25L
  • Complex: Used for complex numbers.
    cplx <- 3 + 4i

Composite Data Types

R also has composite data types such as vectors, lists, data frames, matrices, and arrays.

  • Vector: A collection of elements of the same type.
    vec <- c(1, 2, 3, 4, 5)
  • List: A collection of elements of different types.
    lst <- list(name="John", age=30, isStudent=TRUE)
  • Data Frame: A table-like structure with rows and columns.
    df <- data.frame(name=c("John", "Alice", "Bob"), age=c(30, 25, 28))
  • Matrix: A 2-dimensional array with elements of the same type.
    mat <- matrix(c(1, 2, 3, 4), nrow=2, ncol=2)
  • Array: A multi-dimensional generalization of vectors and matrices.
    arr <- array(1:24, dim=c(2, 3, 4))

Practice Exercises

Now that you've learned about R data types, it's time to practice. Try the following exercises to test your understanding:

  1. Create a numeric vector called ages and assign ages of 5 people to it.
  2. Define a list called person containing the name, age, and gender of a person.
  3. Create a data frame called students with columns name, age, and grade containing information about students.
  4. Make a matrix my_matrix with 3 rows and 2 columns filled with numeric values.