Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've noticed a recurring pattern with people moving into R from a pure math or basic programming background: they tend to treat a data.frame as if it's just a two-dimensional matrix. On the surface, they look identical—rows and columns of data. But if you treat them the same way, you're going to run into some frustrating bugs, usually involving your numbers suddenly turning into text.

Thinking a Data Frame is just a Matrix

In a matrix, every single element must be of the same data type. If you try to mix a number and a string in a matrix, R will silently "coerce" everything into the most flexible type (usually a character). I'll show you exactly what I mean.

# This is a matrix. Watch what happens to the numbers.
employee_matrix <- matrix(c("Alice", 75000, "Bob", 82000), ncol = 2)
print(employee_matrix)
# Output:
#      [,1]    [,2]
# [1,] "Alice" "75000"
# [2,] "Bob"   "82000"

Notice those quotes around "75000"? The matrix forced your salaries to become strings. Now, if you try to calculate the average salary using mean(), R will throw an error or return NA because you can't do math on words. This is the "matrix trap."

A Collection of Vectors Disguised as a Table

A data.frame is fundamentally different. Instead of one big block of a single type, think of it as a list of vectors that happen to have the same length. This allows each column to hold its own data type while still behaving like a table.

# This is a data frame. Types are preserved.
employee_df <- data.frame(
  name = c("Alice", "Bob"),
  salary = c(75000, 82000),
  remote = c(TRUE, FALSE)
)
print(employee_df)
# Output:
#    name salary remote
# 1 Alice  75000   TRUE
# 2   Bob  82000  FALSE

Now, salary remains a numeric vector and remote remains a logical vector. You can perform math on one column without affecting the others. In my experience, the best way to wrap your head around this is to stop seeing a "grid" and start seeing "columns glued together."

Accessing Your Data Without the Headache

Since a data frame is essentially a list of columns, you have a few ways to get your data out. I personally use the $ operator 90% of the time because it's explicit and readable.

If you want the salaries, you just call employee_df$salary. This returns a simple vector. However, if you need to filter rows or select specific columns by index, you'll use the bracket notation [row, column].

# Get the first row only
first_emp <- employee_df[1, ]

# Get the name of the second employee
second_name <- employee_df[2, "name"]

# Calculate the average salary (this works now!)
avg_sal <- mean(employee_df$salary)

One quick tip: when you use [row, ] (leaving the column blank), R gives you a smaller data frame. When you use $column, R gives you a vector. Keeping that distinction clear in your mind will save you hours of debugging when you start building more complex models.




📋 Practical Task

Building a Local Coffee Shop Inventory

You need to organize a small inventory list for a coffee shop. Your goal is to create a data frame that handles different data types correctly and then extract specific information from it.

Requirements:

  • Create a data frame named coffee_inventory with three columns:
    • item (character): "Espresso", "Latte", "Cappuccino"
    • price (numeric): 2.50, 3.75, 3.50
    • in_stock (logical): TRUE, TRUE, FALSE
  • Using the $ operator, calculate the average price of the items.
  • Using bracket notation [row, col], extract the item name of the third product in the list.
  • Print both the average price and the third item's name to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.