SyntaxStudy
Sign Up
R Creating and Inspecting Data Frames
R Beginner 1 min read

Creating and Inspecting Data Frames

A data frame is R's tabular data structure, conceptually similar to a spreadsheet or a SQL table. Each column is a vector (all vectors must have the same length), and columns can be of different types — a numeric column alongside a character column alongside a logical column is perfectly valid. Data frames are the standard input and output of most R modelling and analysis functions, so mastering them is essential. You create a data frame with data.frame(), supplying named vectors as arguments. The resulting object has attributes: names (column names), row.names, and class. The functions dim(), nrow(), ncol(), colnames(), and rownames() interrogate structure, while str() and summary() give a quick overview of the data types and statistical distribution of each column respectively. head() and tail() print the first or last n rows, which is indispensable when working with large datasets. Reading real data into a data frame is usually done with read.csv() or read.table() for delimited files. The readr package provides faster, more informative alternatives (read_csv()). Once in memory, a data frame can be written back to disk with write.csv() or readr's write_csv(). Always inspect a freshly loaded data frame before analysis to catch encoding issues, unexpected column types, or structural problems.
Example
# Creating a data frame
df <- data.frame(
    name    = c("Alice", "Bob", "Carol", "Dave", "Eve"),
    age     = c(28, 34, 22, 41, 30),
    salary  = c(55000, 72000, 48000, 95000, 61000),
    active  = c(TRUE, TRUE, FALSE, TRUE, FALSE),
    dept    = factor(c("HR", "IT", "IT", "Finance", "HR"))
)

# Structure and summary
str(df)         # compact display of types and first values
summary(df)     # descriptive stats per column
dim(df)         # 5 5
nrow(df)        # 5
ncol(df)        # 5
colnames(df)    # "name" "age" "salary" "active" "dept"
rownames(df)    # "1" "2" "3" "4" "5"

# First / last rows
head(df, 3)
tail(df, 2)

# Adding a new column
df$bonus <- df$salary * 0.1

# Modifying a column in place
df$age <- df$age + 1   # everyone ages one year

# Reading / writing CSV (paths are illustrative)
# df2 <- read.csv("employees.csv", stringsAsFactors = FALSE)
# write.csv(df, "employees_out.csv", row.names = FALSE)

# Check for missing values per column
colSums(is.na(df))

# Quick frequency table for a factor column
table(df$dept)