R Tutorial



R DATA FRAMES


Data Frames in R

A Data Frame is a table or a 2D structure in R that can store data of different types (numeric, character, factor, etc.) in each column. It is the most commonly used data structure for storing datasets in R.

Creating a Data Frame

# Create a data frame
students <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(22, 24, 23),
  Score = c(89.5, 92.3, 88.0)
)
  

This creates a table with 3 columns: Name, Age, and Score.

Viewing Data

  • print(students) – View entire data frame
  • head(students) – View first 6 rows
  • str(students) – Structure of data
  • summary(students) – Summary statistics

Accessing Data

  • students$Name – Access "Name" column
  • students[1, ] – First row
  • students[ ,2] – Second column
  • students[2, 3] – 2nd row, 3rd column

Adding Data

# Add a new column
students$Passed <- c(TRUE, TRUE, FALSE)

# Add a new row
new_row <- data.frame(Name="David", Age=21, Score=85.6, Passed=TRUE)
students <- rbind(students, new_row)
  

Modifying Data

# Change a value
students$Score[2] <- 95.0
  

Removing Data

# Remove a column
students$Passed <- NULL

# Remove a row
students <- students[-1, ]
  

Filtering Data

Use conditions to filter rows:

# Students with Score > 90
high_scorers <- students[students$Score > 90, ]
  

Sorting Data

# Sort by Score
students_sorted <- students[order(students$Score), ]
  

Summary

  • Data frames store tabular data with columns of different types.
  • Access data using $, index positions, or logical conditions.
  • You can add, modify, filter, and sort data easily.

Practice Exercises

  • Create a data frame of 5 students with Name, Marks, and Grade.
  • Filter students who scored more than 80.
  • Add a column "Result" that shows "Pass" if Marks ≥ 50.
  • Sort the data frame by descending Marks.
  • Change the Grade of one student and remove another student.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review