§2024-12-04
In R, a data type refers to the kind of value an object can hold, defining how the data is stored and what operations can be performed on it. Below is an explanation of the basic data types in R, along with examples:
The numeric type represents real numbers (i.e., integers and decimals). It is the default type for numbers in R.
Example:
x <- 5 # Integer (also treated as numeric in R) y <- 3.14 # Decimal number (floating-point)
Integers are whole numbers. You can specify an integer by appending an "L" at the end of the number.
Example:
x <- 5L # Integer y <- 10L # Another integer
The character type stores textual data, which are sequences of characters.
Example:
name <- "John" # Character string greeting <- "Hello, World!"
The logical type represents boolean values: TRUE or FALSE.
Example:
a <- TRUE # Logical value b <- FALSE # Another logical value
The complex type represents complex numbers, which have both real and imaginary parts.
Example:
z <- 3 + 2i # Complex number (3 is real, 2 is imaginary)
The raw type is used to represent raw bytes. This is not commonly used for general data manipulation but is useful for low-level data processing.
Example:
raw_data <- charToRaw("hello") # Convert string to raw byte representation
A factor is used for categorical data, such as levels (e.g., "Low", "Medium", "High"). It is used to represent qualitative variables.
Example:
category <- factor(c("Low", "High", "Medium", "Low", "High"))
A list can hold different types of objects and is an ordered collection of elements. Lists can store mixed types (numeric, character, etc.) together.
Example:
my_list <- list(name = "John", age = 25, height = 5.9) # A list with different types
A data.frame is a table-like structure that holds data in a tabular form (like rows and columns). Each column in a data frame can have different data types.
Example:
df <- data.frame(Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 35))
A matrix is a two-dimensional array, where all elements are of the same type (e.g., numeric, character).
Example:
m <- matrix(1:6, nrow = 2, ncol = 3) # Matrix with 2 rows and 3 columns
An array is similar to a matrix, but it can have more than two dimensions.
Example:
arr <- array(1:12, dim = c(3, 2, 2)) # 3x2x2 array
Example Summary
x <- 3.14
y <- 5L
name <- "Alice"
is_adult <- TRUE
z <- 4 + 2i
colors <- factor(c("Red", "Blue", "Green"))
person <- list(name = "Bob", age = 30, height = 5.9)
df <- data.frame(Name = c("Alice", "Bob"), Age = c(25, 30))
matrix_data <- matrix(1:6, nrow = 2, ncol = 3)
array_data <- array(1:12, dim = c(3, 2, 2))
Summary
R supports various data types, allowing you to store and manipulate data efficiently. The most common types are numeric, character, and logical, while others like factor, list, and data.frame provide greater flexibility for more complex data structures.
ChatGPT can make mistakes. Check important info.
Return to Top