Skip to content

Instantly share code, notes, and snippets.

@EarlGlynn
Created January 15, 2014 05:08
Show Gist options
  • Save EarlGlynn/8431150 to your computer and use it in GitHub Desktop.
Save EarlGlynn/8431150 to your computer and use it in GitHub Desktop.
writeLines / readLines examples for KC R Users Group, 2014-01-18
# writeLines / readLines examples described here:
# http://earlglynn.github.io/R/input-output/writeLines-readLines/index.html
#setwd("") # Set working directory if necessary
# Examples:
# 1. Create Sample.csv and Sample.tsv files.
# 2. Verify data correctly writte.
# 3. Read HTML from web page, save to disk.
# efg, 2014-01-13
###########################################################################
### Create Sample.csv and Sample.tsv files for later examples.
# Create character vector
data.lines.comma <- c("Grade,Age,Code,Amount,Start",
"A,23,ABC,48.982,2014-01-01",
"B,56,DEF,2.7183,2014-01-02",
"F,,,0,",
"B,35,XYZ,3.1416,2014-01-05")
data.lines.comma
# Write comma-separated-values (.csv) file to disk
writeLines(data.lines.comma, "Sample.csv")
# Change commas (",") to tabs ("\t")
data.lines.tab <- gsub(",", "\t", data.lines.comma)
data.lines.tab
# Write tab-separated-values (.tsv) file (sometimes .txt or .tab) to disk
writeLines(data.lines.tab, "Sample.tsv")
###########################################################################
### Read csv from disk to verify write was successful
data.lines.copy.comma <- readLines("Sample.csv")
data.lines.copy.comma
# Compare with original
data.lines.copy.comma == data.lines.comma
all(data.lines.copy.comma == data.lines.comma)
### Read tsv from disk to verify write was successful
data.lines.copy.tab <- readLines("Sample.tsv")
data.lines.copy.tab
# Compare with original
data.lines.copy.tab == data.lines.tab
all(data.lines.copy.tab == data.lines.tab)
###########################################################################
### Read HTML from web page. Sample page: R Journal Archive page
s <- readLines("http://journal.r-project.org/archive/")
length(s)
head(s)
tail(s)
tail(head(s,65), 1) # Current issue (for now)
# Save copy locally to look for differences in future
timestamp <- format(Sys.time(), "%Y-%m-%d-%H%M%S")
filename <- paste0("R-Journal-Archive-page-",timestamp,".html")
filename
writeLines(s, filename)
# Example output file: R-Journal-Archive-page-2014-01-13-232402.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment