Data Frames in R
Almost every business dataset you load into R, whether a sales export, a customer list or a survey, arrives as a data frame. Analysis, plotting and model-fitting functions expect this structure. The first practical skill in R analytics is to build a data frame, check what it holds, and pull out the rows and columns a question needs.
What a data frame is
A data frame is R's table. It is a collection of named columns, each column is a vector, and every column has the same length. Each row is one observation, such as an order, a customer or a day. Each column is one variable recorded for every observation. Different columns can hold different types, but within a single column every value has the same type.
To build a small data frame by hand, call data.frame() and give each column a name:
orders <- data.frame(
order_id = c(101, 102, 103, 104),
region = c("East", "West", "East", "North"),
units = c(12, 5, 20, 8),
paid = c(TRUE, FALSE, TRUE, TRUE)
)R prints the result as a grid and numbers the rows on the left:
row | order_id | region | units | paid |
|---|---|---|---|---|
1 | 101 | East | 12 | TRUE |
2 | 102 | West | 5 | FALSE |
3 | 103 | East | 20 | TRUE |
4 | 104 | North | 8 | TRUE |
Inspecting a data frame
Before you analyse a data frame, confirm that its shape and column types are what you expect. These functions answer the usual questions:
Function | What it returns | Result for orders |
|---|---|---|
dim(orders) | rows, then columns | 4 4 |
nrow(orders) | number of rows | 4 |
ncol(orders) | number of columns | 4 |
names(orders) | column names in order | order_id, region, units, paid |
head(orders, 2) | the first rows, still a data frame | rows 1 and 2 |
str(orders) | each column with its type and first values | num, chr, num, logi |
summary(orders) | statistics for each column | minimum, mean, maximum of units, and so on |
The str() output is the quickest type check. Run it right after you import a file. A price column listed as chr (character) instead of num usually means the raw data contains a stray symbol or comma.
Selecting rows and columns
Square brackets take two positions, df[rows, columns]. An empty position means all rows or all columns.
orders[2, ]
orders[, "units"]
orders["units"]
orders[1:2, c("region", "units")]
orders[orders[, "units"] > 10, ]
subset(orders, units > 10)- orders[2, ] returns row 2 as a one-row data frame that keeps all four columns.
- orders[, "units"] returns the units column as a plain numeric vector: 12 5 20 8.
- orders["units"], with only one index, keeps the table shape and returns a data frame with one column and four rows.
- The dollar-sign shortcut, written orders$units, returns the same vector as orders[, "units"].
- orders[1:2, c("region", "units")] returns rows 1 and 2 of two named columns.
- A comparison such as orders[, "units"] > 10 gives one TRUE or FALSE per row: TRUE FALSE TRUE FALSE. In the row position, it keeps rows 1 and 3. subset() does the same filtering with shorter syntax.
Assigning to a column name that does not exist adds a new column. orders[, "revenue"] <- orders[, "units"] * 15 multiplies each row's units by 15 and stores 180, 75, 300 and 120 as a fifth column.
What to remember
- A data frame is a table of equal-length column vectors. Rows are observations and columns are variables.
- Each column holds one type, but different columns can hold different types.
- dim(), nrow(), ncol(), names(), str(), head() and summary() show the shape and contents.
- Index with df[rows, columns]. An empty position means all, and a logical vector in the row position filters rows.
- One column selected with a comma comes back as a vector. A single index or drop = FALSE keeps a data frame.
Example: Checking and subsetting an inventory data frame
A hardware store exports its inventory into R with this code:
inventory <- data.frame(
sku = c("H-01", "H-02", "P-10", "P-11", "T-05"),
category = c("Hand tool", "Hand tool", "Paint", "Paint", "Tile"),
stock = c(14, 6, 0, 22, 9),
price = c(4.50, 12.00, 7.25, 3.00, 20.00)
)a) What does dim(inventory) return, and what does each number mean?
The call to data.frame() receives ________ named vectors, so the data frame has four columns. Each vector holds ________ values, so the data frame has five rows. dim() reports rows first and columns second.
dim(inventory) therefore returns 5 4. The data frame records five items (observations) and four variables about each item: sku, category, stock and price.
b) Write an expression that keeps only the items with fewer than 10 units in stock. Which SKUs does it return?
First build the logical vector inventory[, "stock"] < 10. Comparing 14, 6, 0, 22 and 9 with 10 gives ________.
Put that vector in the row position and leave the column position empty to keep every column: inventory[inventory[, "stock"] < 10, ]. subset(inventory, stock < 10) gives the same result.
The TRUE values are in positions 2, 3 and 5, so the result is a data frame with ________ rows and all four columns. The SKUs that need reordering are H-02, P-10 and T-05.
c) Add a column named value that equals stock times price, and find the total value of the inventory.
Assigning to a new column name creates the column: inventory[, "value"] <- inventory[, "stock"] * inventory[, "price"]. R multiplies the two columns element by element, row by row:
- H-01: 14 × 4.50 = ________
- H-02: 6 × 12.00 = ________
- P-10: 0 × 7.25 = 0
- P-11: 22 × 3.00 = ________
- T-05: 9 × 20.00 = ________
The data frame now has ________ columns. sum(inventory[, "value"]) adds 63 + 72 + 0 + 66 + 180, so the total inventory value is 381 dollars.
Type each function name only, without parentheses or arguments. You have just imported a customer file into R as a data frame called customers. To confirm its shape in one call, you pass customers to the function named , which returns the number of rows and then the number of columns. To build a small data frame by hand from named vectors of equal length, you pass those vectors to the function named .
A small HR team stores its staff records in R with the code below. What does the last line return?
staff <- data.frame(
name = c("Ana", "Ben", "Cai", "Dee"),
dept = c("Sales", "IT", "HR", "IT"),
salary = c(52000, 61000, 48000, 67000)
)
staff[3, ]