Data Frames in R

 

Data Frames in R

Introduction

A data frame is one of the most important and widely used data structures in R. It is used to store data in a tabular form, similar to a spreadsheet or a database table.

A data frame consists of:

  • Rows → observations or records.
  • Columns → variables or attributes.

Unlike matrices, columns in a data frame may contain different data types. Thus, a data frame is a heterogeneous two-dimensional data structure.

For example, consider a student database:

RollNoNameMarksPassed
101John85TRUE
102Mary92TRUE
103Alex45FALSE

Here:

  • RollNo → integer
  • Name → character
  • Marks → numeric
  • Passed → logical

Characteristics of Data Frames

  • Two-dimensional structure.
  • Rows represent observations.
  • Columns represent variables.
  • Columns may have different data types.
  • Columns must have equal lengths.
  • Similar to a table in a relational database.
  • Most machine learning datasets are stored as data frames.

Creating a Data Frame

Data frames are created using the data.frame() function.

Syntax

data.frame(column1, column2, ...)

Example 1: Student Data

student <- data.frame(
RollNo = c(101,102,103),
Name = c("John","Mary","Alex"),
Marks = c(85,92,78),
Passed = c(TRUE,TRUE,TRUE)
)

print(student)

Output

  RollNo Name Marks Passed
1 101 John 85 TRUE
2 102 Mary 92 TRUE
3 103 Alex 78 TRUE

Structure of a Data Frame

str(student)

Output

'data.frame': 3 obs. of 4 variables:
$ RollNo: num 101 102 103
$ Name : chr "John" "Mary" "Alex"
$ Marks : num 85 92 78
$ Passed: logi TRUE TRUE TRUE

Determining Properties

class()

class(student)

Output

[1] "data.frame"

dim()

Returns rows and columns.

dim(student)

Output

[1] 3 4

nrow()

nrow(student)

Output

[1] 3

ncol()

ncol(student)

Output

[1] 4

names()

Returns column names.

names(student)

Output

[1] "RollNo" "Name" "Marks" "Passed"

Accessing Columns

Using $

student$Name

Output

[1] "John" "Mary" "Alex"

Using Column Index

student[,2]

Output

[1] "John" "Mary" "Alex"

Using Column Name

student[,"Marks"]

Output

[1] 85 92 78

Accessing Rows

student[2,]

Output

RollNo Name Marks Passed
2 102 Mary 92 TRUE

Accessing Individual Elements

student[2,3]

Output

[1] 92

(Row 2, Column 3)


Access Multiple Rows and Columns

student[1:2,2:3]

Output

  Name Marks
1 John 85
2 Mary 92

Adding a New Column

student$Age <- c(20,21,22)

print(student)

Output

  RollNo Name Marks Passed Age
1 101 John 85 TRUE 20
2 102 Mary 92 TRUE 21
3 103 Alex 78 TRUE 22

Modifying a Column

student$Marks <- c(90,95,80)

print(student)

Deleting a Column

student$Age <- NULL

print(student)

Adding Rows

new_row <- data.frame(
RollNo=104,
Name="David",
Marks=88,
Passed=TRUE
)

student <- rbind(student,new_row)

print(student)

Combining Columns

height <- c(170,165,175)

student <- cbind(student,height)

print(student)

Sorting Data Frames

Sort by Marks

student[order(student$Marks),]

Ascending order.


Descending Order

student[order(student$Marks,decreasing=TRUE),]

Logical Indexing

Students with Marks Greater than 80

student[student$Marks>80,]

Output

  RollNo Name Marks Passed
1 101 John 85 TRUE
2 102 Mary 92 TRUE

Students Whose Names Start with A

student[substr(student$Name,1,1)=="A",]

Output

  RollNo Name Marks Passed
3 103 Alex 78 TRUE

Display Only Names

student$Name

or

student[,"Name"]

Statistical Functions

Mean Marks

mean(student$Marks)

Maximum Marks

max(student$Marks)

Minimum Marks

min(student$Marks)

Standard Deviation

sd(student$Marks)

Summary of Data Frame

summary(student)

Output

RollNo          Name               Marks
Min. :101.0 Length:3 Min. :78
1st Qu.:101.5 Class :character
Median :102.0
Mean :102.0
Max. :103.0

Reading Data Frames from Files

CSV File

Suppose students.csv contains:

RollNo,Name,Marks
101,John,85
102,Mary,92
103,Alex,78

Read it using:

student <- read.csv("students.csv")

print(student)

Writing Data Frames to CSV

write.csv(student,"students.csv")

Applying Functions to Columns

sapply(student,is.numeric)

Output

RollNo Name Marks Passed
TRUE FALSE TRUE FALSE

Head and Tail

First Six Rows

head(student)

Last Six Rows

tail(student)

Difference Between Matrix and Data Frame

FeatureMatrixData Frame
Data TypeHomogeneousHeterogeneous
DimensionsTwoTwo
Column NamesOptionalPresent
Data TypesSameDifferent
Used InNumerical ComputingData Analysis

Applications of Data Frames

Student Database

Rows → Students

Columns → Roll Number, Name, Marks

Employee Records

Rows → Employees

Columns → Name, Salary, Department

Sales Data

Rows → Transactions

Columns → Product, Quantity, Price

Machine Learning

Rows → Samples

Columns → Features

Healthcare

Rows → Patients

Columns → Age, Weight, Blood Pressure


Important Functions

FunctionPurpose
data.frame()    Create data frame
str()    Structure
dim()    Dimensions
nrow()    Number of rows
ncol()    Number of columns
names()    Column names
summary()    Statistical summary
head()    First rows
tail()    Last rows
order()    Sort
rbind()    Add rows
cbind()    Add columns
read.csv()    Read CSV
write.csv()    Write CSV

Conclusion

A data frame is the most widely used data structure in R for storing and analyzing tabular data. It combines the flexibility of lists with the two-dimensional structure of matrices, making it ideal for statistics, machine learning, data analysis, and scientific computing. Understanding data frames is essential because almost all real-world datasets in R are represented as data frames.

Comments

Popular posts from this blog

Statistical Methods Lab ( R Language) PCCBL308 Semester 3 KTU BTech CB and CU 2024 Scheme - Dr Binu V P

Programs in R - using control statements - Assignment 2

Basic R Programs to Try - Assignment 1