# Construct a data frame where each argument defines a column name and its vector of values
df <- data.frame(
name1 = vector1, # First column named name1
name2 = vector2, # Second column named name2
name3 = vector3 # Third column named name3
)38 Data frame
Tableau pratique
The previous chapters mirrors mathematical concepts in programming, such as vectors, matrices, logical and numeric values, and matrix operations. This chapter transitions from mathematical structures to the more flexible requirements of data science. The data frame was developed to meet these needs, and most data encountered in ecological practice are stored in this format.
A data frame stores multiple variables recorded across multiple observations. For instance, an investigator surveys 100 individuals and records name, age, and sex. The dataset consists of three columns: the first for name as character, the second for age as integer, and the third as logical (TRUE if female and FALSE if male). Similarly, a field researcher visits fifteen sites and records site name, altitude, pH, and other variables.
A data frame is a rectangular structure (similar to a matrix Chapter 5 and Chapter 36), where each column represents a variable. However, unlike a matrix, the data type of each column can differ.
Another practical advantage of a data frame is that columns typically have names, allowing access by column name rather than numerical index.
Formal
A data frame is constructed with the function data.frame().
The constraint is that all vectors must have equal lengths; otherwise, the structure will not form a rectangle and the operation will fail.
Columns can be conveniently accessed using df$name1, which is the most common approach. Due to underlying data structures, this is equivalent to df[, 1] or df["name1"].
Examples
Below are three styles for creating a data frame. The third approach represents standard best practice.
1- The quickest approach is to type directly each vector in the function. The code is shorter but the column names are usually a mess.
# Method 1: Data frame created without specifying column names, resulting in default, uninformative names my_df <- data.frame( c(1, 2, 3), c("A", "X", "B"), c(TRUE, TRUE, FALSE)) my_dfc.1..2..3. c..A....X....B.. c.TRUE..TRUE..FALSE. 1 1 A TRUE 2 2 X TRUE 3 3 B FALSE- A more organized approach is to contruct the vector first and then add the vector name in the function. Ideally the vector name should be information which is not the case here.
# Method 2: Data frame created using existing vector names as column names col1 <- c(1, 2, 3) col2 <- c("A", "X", "B") col3 <- c(TRUE, TRUE, FALSE) my_df <- data.frame(col1, col2, col3) my_dfcol1 col2 col3 1 1 A TRUE 2 2 X TRUE 3 3 B FALSE- The third method assigns a column name to each vector/variable.
# Method 3: Data frame created with explicit, descriptive variable names my_df <- data.frame( id = col1, letter = col2, male = col3) my_dfid letter male 1 1 A TRUE 2 2 X TRUE 3 3 B FALSEDifferent manners to extract column. The first approach represents standard best practice but can only extract one column. The remaning approach allows to extract more columns1
# Extract a column using the dollar sign ($) operator (returns a vector) my_df$id[1] 1 2 3# Extract the first column using matrix-style numerical indexing (returns a vector) my_df[, 1][1] 1 2 3# Subset a column by name using single brackets (returns a 1-column data frame) my_df["id"]id 1 1 2 2 3 3# Extract a column by name using matrix-style character indexing (returns a vector) my_df[, "id"][1] 1 2 3# Extract two column by name using matrix-style character indexing (returns a 2-column data frame) my_df[, c("id", "letter")]id letter 1 1 A 2 2 X 3 3 BAppending a new column to a data frame
# Add a new column (variable) to the data frame my_df$name <- c("Andry", "Feno", "Felana") my_dfid letter male name 1 1 A TRUE Andry 2 2 X TRUE Feno 3 3 B FALSE Felana
Tips and warnings
Column names are considered variables and should not include spaces or special characters; the same rules apply as in Chapter 29.
In principle, all input vectors when constructing a data frame should be of equal length. There is a special case where a vector of length one is provided: R creates a constant vector matching the length of the longest vector.
# Construct a data frame using a scalar (recycled) and a multi-element vector data.frame(constant = 1, letters = c("A", "B", "C"))constant letters 1 1 A 2 1 B 3 1 CA
tibbleis a common variation of the data frame structure. The popular package ecosystemtidyverseprefers data formatted as a tibble, but standard data frames also work. The differences are subtle enough that either format can be used in most workflows.A character vector is often converted into a factor (see last tip in Chapter 35).
The basic concepts above are useful for understanding the core structure and goals of this volume. However, manual entry is not the ideal method for entering data into R. Most often, data are entered in spreadsheet software such as Excel and subsequently imported into R as a data frame.
With dplyr, selecting columns is done with the function select↩︎