पाठ 6 / 25

Data Frames and Tibbles

Create, inspect and subset data frames and tibbles.

Tables of data

A data frame is R's central structure for tabular data: a list of equal-length columns, each column a vector of one type, with rows representing observations. Create one with data.frame() or read it from a file. Inspect with head(), tail(), nrow(), ncol(), dim(), names(), str(), summary() and, in the tidyverse, glimpse(). Access a column with df$column or df[["column"]], and subset rows and columns with df[rows, cols], for example df[df$total > 500, c("id", "city")]. A tibble is the tidyverse's modern data frame: it prints more helpfully (types shown, only the first rows), never converts strings to factors, never partially matches column names, and complains loudly about mistakes. Most tidyverse functions return tibbles, and they work anywhere a data frame is expected. Large datasets can also use data.table (very fast) or the Arrow and DuckDB integrations for data larger than memory.

Creating and exploring a tibble

Base R subsetting and tidyverse inspection side by side.

library(tibble)
library(dplyr)

orders <- tibble(
  id = c("o1", "o2", "o3", "o4"),
  city = c("Pune", "Delhi", "Pune", "Mumbai"),
  total = c(1200, 300, 800, 2500),
  paid = c(TRUE, FALSE, TRUE, TRUE)
)

glimpse(orders)                         # column types and first values
summary(orders$total)
nrow(orders)                            # 4

orders$total * 1.18                      # a column is just a vector
orders[orders$total > 500, c("id", "city")]   # base R subsetting
mean(orders$total[orders$paid])          # average of paid orders: 1500

orders$size <- ifelse(orders$total > 1000, "large", "small")   # add a column

Prefer tibbles for new code

Base data frames silently allow df$tot to match a column named total (partial matching). Tibbles refuse and return NULL with a warning, catching typos early.

त्वरित जाँच: What is a data frame in R?

  • A list of equal-length column vectors forming a table
  • A matrix of characters
  • A plot type
  • A package
Answer

A list of equal-length column vectors forming a table — Each column is a vector, and all columns have the same length.