Data frames
โ Report an issue with this lessoncourses <- data.frame(
title = c("HTML", "SQL", "Python"),
price = c(29.99, 59.99, 29.99),
level = c("beginner", "intermediate", "beginner")
)
print(courses[courses$level == "beginner", ])
print(mean(courses$price))
A data frame is a table -- rows and named columns, R's equivalent of a spreadsheet or a SQL result set, and the structure almost all real R analysis is built around.
A data frame is really a list of equal-length vectors, one per column, each of which can hold a different type -- so a "price" column can be numeric while a "title" column is character data, all within the same table. There are several ways to inspect and slice one:
str(courses) # shows column names, types, and a preview of values
nrow(courses) # number of rows
ncol(courses) # number of columns
head(courses, 2) # first 2 rows
courses$title # the title column, as a plain vector
courses[["price"]] # equivalent way to pull a single column
courses[1, ] # the first row, all columns
courses[, "price"] # the price column, all rows -- note the comma placement
The comma inside [ , ] matters a lot: everything before
it selects rows, everything after selects columns.
courses[courses$level == "beginner", ] reads as "give me the
rows where level equals beginner, and all columns" -- leaving the part
after the comma blank means "all columns."
Adding a new column is as simple as assigning to a name that doesn't exist yet, and it's automatically vectorized across every row:
courses$discounted_price <- courses$price * 0.8
courses$is_premium <- courses$price > 50
merge() joins two data frames together on a shared
column, similar to a SQL JOIN:
enrollments <- data.frame(title = c("HTML", "SQL"), students = c(120, 80))
merge(courses, enrollments, by = "title") # inner join on the title column
Try it yourself
Run your code and get it working before marking this lesson complete.
9 more lessons โ including Capstone project: analyze a course catalog โ plus a certificate are waiting.
Unlock the full course โ $149.99