R — Reading and writing lines in files
In R, writeLines writes character elements as lines and readLines reads them back as a character vector. Convert the required lines to numbers before totaling them.
A simple example
Read back one letter
- Start with A
- Do this Write, then read
- Result A
path <- tempfile()
writeLines("A", path)
cat(readLines(path))
unlink(path)
A
Sum two lines from a temporary report
writeLines writes each element as a separate line. readLines returns a character vector. Remove blank strings before converting to integer. on.exit schedules cleanup inside the function.
Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.
Run the example
R 4. Run these commands from the directory containing the example.
Rscript Lesson.R
sum_report <- function() {
path <- tempfile()
on.exit(unlink(path))
writeLines(c("4", "7"), path)
lines <- trimws(readLines(path))
sum(as.integer(lines[nzchar(lines)]))
}
cat(sum_report(), "\n", sep = "")
11
The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.
Try it yourself
Add a third line containing 12.
Check your answer
The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.