Data Frames in R

📘 Introduction

A data frame is one of the most important data structures in R. It is a two-dimensional table consisting of rows and columns, where each column can store a different data type. Data frames are widely used in data analysis, statistics, machine learning, and data visualization because they closely resemble spreadsheet tables and database tables.

Information

A data frame is a collection of vectors of equal length. Each column represents a variable, while each row represents an observation or record.

đŸŽ¯ Why Use Data Frames?

  • Store structured tabular data.
  • Allow different data types in different columns.
  • Simplify data manipulation and analysis.
  • Serve as the primary data structure for statistical computing.
  • Integrate seamlessly with R packages such as dplyr and ggplot2.

đŸ“Ļ Creating a Data Frame

The data.frame() function is used to create a data frame. Each column is defined as a vector, and all columns must have the same number of elements.

Creating a Data Frame

students <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(21, 22, 20),
  Marks = c(85, 90, 88)
)

print(students)

Output

Console Output

Name Age Marks
1    Alice  21    85
2      Bob  22    90
3  Charlie  20    88

📊 Structure of a Data Frame

Data Frame
Rows (Observations)
Columns (Variables)
Column Types
Numeric
Character
Logical
Factor

🔍 Viewing Data Frame Information

FunctionDescriptionExample
str()Displays the structure.str(df)
summary()Displays summary statistics.summary(df)
head()Shows the first six rows.head(df)
tail()Shows the last six rows.tail(df)
dim()Returns the dimensions.dim(df)
names()Returns column names.names(df)

Viewing Data Frame Information

students <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(21,22,20),
  Marks = c(85,90,88)
)

str(students)
summary(students)
head(students)
tail(students)
dim(students)
names(students)

đŸŽ¯ Accessing Data

Data in a data frame can be accessed by column name, row and column indexes, or the $ operator.

Using $

students$Name
students$Marks

Using Indexes

students[2,3]
students[1,]
students[,2]

Using Column Names

students[, "Marks"]
students[, c("Name","Age")]

âœī¸ Adding Columns

A new column can be added by assigning values to a new column name.

Adding a Column

students$Grade <- c("A", "A+", "A")

print(students)

➕ Adding Rows

Use the rbind() function to append a new row.

Adding a Row

students <- data.frame(
  Name = c("Alice", "Bob"),
  Age = c(21,22),
  Marks = c(85,90)
)

new_student <- data.frame(
  Name = "Charlie",
  Age = 20,
  Marks = 88
)

students <- rbind(students, new_student)

print(students)

❌ Removing Columns

Removing a Column

students$Marks <- NULL

print(students)

❌ Removing Rows

Removing a Row

students <- students[-2, ]

print(students)

🔄 Updating Data

Updating Values

students$Marks[1] <- 95

students[2, "Age"] <- 23

print(students)

🔍 Selecting Rows Using Conditions

Rows can be filtered using logical conditions.

Filtering Data

students <- data.frame(
  Name = c("Alice","Bob","Charlie"),
  Marks = c(85,90,75)
)

students[students$Marks >= 85, ]

📊 Useful Data Frame Functions

FunctionDescription
nrow()Returns the number of rows.
ncol()Returns the number of columns.
dim()Returns dimensions.
names()Returns column names.
str()Displays the structure.
summary()Displays summary statistics.

Useful Functions

print(nrow(students))
print(ncol(students))
print(dim(students))
print(names(students))
summary(students)

🧭 Data Frame Workflow

Create a Data Frame
Add Rows and Columns
Access Data
Modify Values
Filter Records
Analyze Data

🌍 Real-World Example

The following data frame stores employee information for a company.

Employee Data

employees <- data.frame(
  ID = c(101,102,103),
  Name = c("John","Sophia","David"),
  Department = c("HR","Finance","IT"),
  Salary = c(45000,62000,58000),
  Active = c(TRUE, TRUE, FALSE)
)

print(employees)

summary(employees)

employees[employees$Salary > 50000, ]

📋 Matrix vs Data Frame

FeatureMatrixData Frame
DimensionsTwo-dimensionalTwo-dimensional
Data TypesSingle type onlyDifferent types per column
Rows and ColumnsYesYes
Primary UseMathematical computationsTabular data analysis

âš ī¸ Common Mistakes

MistakeExplanationSolution
Columns with unequal lengthsAll columns must contain the same number of rows.Ensure every column has equal length.
Using invalid column namesMisspelled names produce errors.Check column names using names().
Removing important columns accidentallyAssigning NULL deletes the column.Verify before removing data.
Confusing matrices with data framesMatrices store only one data type.Use data frames when columns have different data types.

💡 Best Practices

  • Use meaningful column names.
  • Store related information in the same data frame.
  • Inspect the structure using str() before analysis.
  • Use logical conditions to filter data efficiently.
  • Keep data clean by removing duplicate or unnecessary records.

Best Practice

Data frames are the foundation of data analysis in R. Organizing data into well-structured data frames makes cleaning, visualization, statistical analysis, and machine learning much more efficient.

📝 Summary

Data frames are versatile two-dimensional data structures that allow each column to store a different data type while maintaining equal-length rows. You learned how to create data frames, inspect their structure, access and modify data, add or remove rows and columns, filter records, and use essential functions for data analysis. Because most real-world datasets are stored in tabular form, mastering data frames is one of the most important skills in R programming.

>>"Well-structured data frames are the foundation of effective data analysis and informed decision-making."