R is a dynamically typed language, which means that variables do not have fixed types, and their data types are determined by the values they hold. R supports a wide range of data types. Here are some of the most common data types in R:
Numeric: Numeric data types are used to store numbers, both integers and decimals (floating-point numbers).
x <- 42 # integer
y <- 3.14 # floating-point number
Character: Character data types are used to store text and are enclosed in either single or double quotes.
name <- "John"
Logical: Logical data types represent Boolean values, which can be either TRUE or FALSE.
is_ready <- TRUE
Integer: In addition to the general numeric type, R has a separate integer type to store whole numbers.
count <- as.integer(10)
Complex: Complex data types are used to store complex numbers with real and imaginary parts.
z <- 2 + 3i
Factor: Factor data types are used for categorical variables with a fixed number of levels. They are particularly useful for statistical analysis.
gender <- factor(c("Male", "Female", "Male", "Female"))
Date and Time: R provides various data types and functions for working with date and time data, including Date, POSIXct, and POSIXlt.
today <- Sys.Date() # Date
now <- Sys.time() # Date and time
Vector: A vector is a fundamental data structure in R that can hold elements of the same data type. Vectors can be of type numeric, character, logical, etc.
numbers <- c(1, 2, 3, 4, 5)
names <- c("Alice", "Bob", "Charlie")
List: A list is a data structure that can hold elements of different data types. It is a versatile way to store heterogeneous data.
info <- list(name = "John", age = 30, is_student = FALSE)
Matrix: A matrix is a two-dimensional data structure that stores elements of the same data type.
matrix_data <- matrix(1:6, nrow = 2, ncol = 3)
DataFrame: A data frame is a two-dimensional, tabular data structure similar to a spreadsheet or SQL table. It can hold different data types in its columns.
df <- data.frame(Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 35))
Array: An array is a multi-dimensional data structure that can hold elements of the same data type. It is a generalization of a matrix.
arr <- array(1:12, dim = c(2, 3, 2))
These are some of the fundamental data types in R, and there are many more specialized data types and structures available in R packages. Understanding the different data types is essential for effective data manipulation and analysis in R.