Exploring R Data Frames: A Beginner's Guide

Lesson Overview and Goals

Hello there! Today, our focus is the backbone of R programming: data frames. These store tabular data. By the end of this lesson, you'll be familiar with the construction and manipulation of data frames and reiterate their importance in your journey of data exploration.

Data Frames: A First Look

A data frame in R holds data in a manner similar to how a picture frame holds a photo. They are two-dimensional, with each column accommodating one variable and each row containing one set of values from each column. This is like a combination of vectors and matrices, allowing for columns of varied data types.

Consider this scenario: you're hosting a party. A matrix can't store both your friends' names (which are characters) and their numbers (which are integers); a data frame, however, solves this problem aptly.

Creating a Data Frame

We construct data frames using R's data.frame() function. Each column consists of a vector of values. Sticking with our party analogy, we create a data frame:

# Vectors for the party attendees
friends <- c("Alice", "Bob", "Charlie")
attend <- c("Yes", "No", "Yes")
guests <- c(2, 0, 3)

# Construct a data frame
party_df <- data.frame(Friends=friends, Attending=attend, Guests=guests)

# Inspect the data frame
print(party_df)

The output is:

  Friends Attending Guests
1   Alice       Yes      2
2     Bob        No      0
3 Charlie       Yes      3

Providing explicit column names such as Friends=friends, Attending=attend, and Guests=guests makes the data frame easy to understand.

Accessing Data

To access a data frame's content, R uses names or indices and conditions. Data can be modified, and additional columns and rows can be added. For example:

# Access 1st column by index
party_df[[1]]  # [1] "Yes" "No"  "Yes"

# Access 'Friends' column by name
party_df$Friends  # [1] "Alice"   "Bob"     "Charlie"

# Subset where attend is 'Yes'
subset(party_df, Attending == 'Yes')
#   Friends Attending Guests
# 1   Alice       Yes      2
# 3 Charlie       Yes      3

Adding Columns

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal