Menu
CoddyTech

Data Frames

Lesson 20 of 48 in Coddy's R for C++ Developers course.

C++ can represent a table as a vector of records or maintain parallel columns with a shared length invariant. An R data.frame organizes equal-length columns and supports row/column selection. Selecting one column may drop dimensions; use drop=FALSE when the result must remain a table. R row positions start at one.

C++

#include <iostream>
#include <vector>
#include <string>
struct Row{std::string name;int score;};

int main(){
std::vector<Row> rows{{"tea",2},{"cake",5}};std::cout<<rows.size()<<":"<<rows[1].name<<"\n";
}

R

frame <- data.frame(name=c("tea","cake"), score=c(2,5))
cat(nrow(frame[2, , drop=FALSE]), ncol(frame), "\n")

Use drop=FALSE when later code requires a data frame.

challenge icon

Challenge

Easy

Implement select_rows(frame,minimum) returning the name column for rows whose score is at least minimum, in original order. Input first token is minimum; remaining tokens are name:score. Empty selection prints empty.

Keep the declared public API. The visible locked driver checks it directly as well as printing solve(lines). Inputs satisfy the stated contract; all arithmetic is small and finite.

Your code goes in Functions.R and Exercise.R. main.R sources dependencies in order and holds the supplied input/output code; it cannot be edited.

Try it yourself

source("Functions.R")
source("Exercise.R")
stopifnot(identical(select_rows(data.frame(name=c("a","b"),score=c(5,8)),6),"b"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in R for C++ Developers

Practice on your own: Online R compiler