Menu
Coddy logo textTech

Working With Files

Part of the Object Oriented Programming section of Coddy's R journey. Lesson 1 of 57.

Real programs are split into several files. In R, source("Greeting.R") runs another file from top to bottom, and every function that file defines is available afterwards:

# Greeting.R
greeting <- function(name) {
  paste0("Hello, ", name, "!")
}

# main.R
source("Greeting.R")
cat(greeting("Ada"), "\n")

Running main.R prints Hello, Ada!: the source() line loads greeting() before main.R calls it.

The program starts in the file you run, here main.R, and R reads it line by line. Order matters: a function exists only after the file that defines it has been sourced, so the source() lines go at the top:

# main.R
cat(greeting("Ada"), "\n")   # Error: could not find function "greeting"
source("Greeting.R")
cat(greeting("Ada"), "\n")   # works: greeting() now exists

The usual layout is one class per file, named after the class: Account.R holds the account constructor and its methods, Shape.R holds the shape generics. In this section's challenges your code goes in those files, and main.R holds the supplied input/output code, with the source() lines already at its top in the right order. The editor shows each file as a tab.

Shape.R      # generics shared by every shape: source it first
Circle.R     # the circle class and its methods
main.R       # source("Shape.R"); source("Circle.R"); reads input, prints results

source() runs a file in the global environment, so its functions and variables become global names. R has no file-private names: if two files define helper(), the file sourced last wins. A value on its own line in a sourced file is not printed either, so files that should show something call cat():

# Tools.R
total <- 0                 # a global variable once sourced
42                         # not printed by source()
helper <- function(x) x * 2

# Other.R
helper <- function(x) x + 1   # sourced later: replaces the helper above
challenge icon

Challenge

Easy

The program has two files. main.R sources Greeting.R, reads names and prints the result of greeting(name) for each. Complete greeting() in Greeting.R so it returns Hello, Ada! for the name Ada, or Hello, friend! when the name is empty.

Your code goes in Greeting.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Greeting.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
for (name in input) cat(greeting(name), "\n", sep = "")
quiz iconTest yourself

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

All lessons in Object Oriented Programming

Practice on your own: Online R compiler