Creating Data Frames
Part of the Logic & Flow section of Coddy's R journey. Lesson 42 of 64.
A data frame is R's table: every column is a vector with its own type, and all columns have the same length, one value per row. data.frame() builds one from named vectors:
people <- data.frame(
name = c("ada", "bo", "cy"),
age = c(36, 22, 41),
city = c("london", "paris", "rome")
)
print(people)Output:
name age city
1 ada 36 london
2 bo 22 paris
3 cy 41 romenrow() and ncol() give the size, and names() lists the columns. Unlike a matrix, the columns can hold different types: here text and numbers.
people <- data.frame(
name = c("ada", "bo", "cy"),
age = c(36, 22, 41),
city = c("london", "paris", "rome")
)
print(nrow(people))
print(ncol(people))
print(names(people))Output:
[1] 3
[1] 3
[1] "name" "age" "city"str() shows the type and the first values of every column, which is a quick way to check what a data frame holds:
people <- data.frame(
name = c("ada", "bo", "cy"),
age = c(36, 22, 41),
city = c("london", "paris", "rome")
)
str(people)Output:
'data.frame': 3 obs. of 3 variables:
$ name: chr "ada" "bo" "cy"
$ age : num 36 22 41
$ city: chr "london" "paris" "rome"Data often arrives as text with one row per line. read.csv(text = lines) turns such lines into a data frame, using the first line as the column names and converting numbers automatically:
lines <- c("item,qty", "tea,2", "jam,5")
orders <- read.csv(text = lines)
print(orders)
print(sum(orders$qty))Output:
item qty
1 tea 2
2 jam 5
[1] 7Challenge
EasyComplete table_info(names, ages). Build a data frame with the columns name and age from the two vectors. Return three lines: Rows: with the number of rows, Columns: with the column names joined by , , and Oldest: with the name in the row with the largest age (the first one when ages tie).
The supplied code reads the names and the ages as two comma-separated lines and prints each returned line.
Try it yourself
table_info <- function(names, ages) {
# Write your code here
character(0)
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(table_info(strsplit(input[1], ",")[[1]], as.numeric(strsplit(input[2], ",")[[1]])), sep = "\n")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler