February 15, 2019

R language - Reading from files & Writing to files

Reading from files & Writing to files in R

readLines(con = stdin(), n = -1L, ok = TRUE, warn = TRUE, encoding = "unknown", skipNul = FALSE)
readLines(tmp)
vec<-readLines("test.txt")
readLines("exam.dat", n = -1)
A <- readLines(con <- file("Unicode.txt", encoding = "UCS-2LE"))
my.age <- readline(prompt="Enter age: ")
text <- readLines("file.txt",encoding="UTF-8")

writeLines(text, con = stdout(), sep = "\n", useBytes = FALSE)
writeLines(x)
output <- writeLines("hello\n\U1F30D")
writeLines(x, con = tmp)
writeLines(letters, sep = "***")
writeLines(x, con = tmp, sep = "\r\n")
writeLines("abc", zz)
writeLines(test1, tf)
writeLines(line, con="/data/mlines.txt")

readChar(con, nchars, useBytes = FALSE)
readChar(zz, nc)
readChar(zz, nchar(x)+3)

writeChar(object, con, nchars = nchar(object, type = "chars"), eos = "", useBytes = FALSE)
writeChar(x, zz, nc, eos = NULL)
writeChar(x, zz, eos = "\r\n")

readBin(con, what, n = 1L, size = NA_integer_, signed = TRUE,  endian = .Platform$endian)
readBin(zz, integer(), 6)
readBin(zz, numeric(), size = 4, endian = "swap")
readBin(zz, integer(), 7, size = 2, signed = FALSE)

writeBin(object, con, size = NA_integer_, endian = .Platform$endian, useBytes = FALSE)
writeBin(1:10, zz)
writeBin("A test of a connection", zz)
writeBin(pi^2, zz, size = 4, endian = "swap")
z <- writeBin(c("a", "test", "of", "character"), raw())

sink(file = NULL, append = FALSE, type = c("output", "message"), split = FALSE)
sink("/data/sinkfile.txt")
sink()
sink(con)
sink(con, type = "message")
sink(type = "message")
sink.number(type = c("output", "message"))

scan function # Read data into a vector or list from the console or file.
scan(file = "", what = double(), nmax = -1, n = -1, sep = "", quote = if(identical(sep, "\n")) "" else "'\"", dec = ".", skip = 0, nlines = 0, na.strings = "NA", flush = FALSE, fill = FALSE, strip.white = FALSE, quiet = FALSE, blank.lines.skip = TRUE, multi.line = TRUE, comment.char = "", allowEscapes = FALSE, fileEncoding = "", encoding = "unknown", text, skipNul = FALSE)
nums = scan()
chars = scan(what="character")
scan(text = "11 2 34 999999")
vect <- scan("file.txt")
pp <- scan("exam.dat", skip = 1, quiet = TRUE)
scan(f9, what=double(), nlines=100)
scan("exam.dat", skip = 1, nlines = 1) # only 1 line after the skipped one
scan("exam.dat", what = list("","",""))
scan("exam.dat", what = list("","",""), flush = TRUE)
scan("file.txt", character(0), sep = "\n")

unlink("testbin")
unlink("filename.txt")

cat(... , file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)
cat(i, "+", i, "=", i+i, "\n")
cat("iteration = ", iter <- iter + 1, "\n")
cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))
cat("TITLE extra line", "2 3 5 7", "11 13 17", file = "example.dat", sep = "\n")
cat(text,file="file.txt",sep="\n")

file(description = "", open = "", blocking = TRUE, encoding = getOption("encoding"), raw = FALSE, method = getOption("url.method", "default"))
zz <- file("testchar", "wb")
zz <- file("testchar", open="r")
con <- file("test1", "r", blocking = FALSE)
con <- file("Unicode.txt", encoding = "UCS-2LE")
con <- file("women22", "w")

open(con, ...)
open(con, open = "r", blocking = TRUE, ...)

open type
"r" or "rt" # Open for reading in text mode
"w" or "wt" # Open for writing in text mode
"a" or "at" # Open for appending in text mode
"rb" # Open for reading in binary mode
"wb" # Open for writing in binary mode
"ab" # Open for appending in binary mode
"r+", "r+b" # Open for reading and writing
"w+", "w+b" # Open for reading and writing, truncating file initially
"a+", "a+b" # Open for reading and appending

close(con, type = "rw", ...)
close(zz)

seek(Tfile, 0, rw = "r")

url(description, open = "", blocking = TRUE, encoding = getOption("encoding"), method = getOption("url.method", "default"))

gzfile(description, open = "", encoding = getOption("encoding"), compression = 6)
con <- gzfile("women.rds")
con <- gzfile("women.rds", "rb")
readLines(zz <- gzfile("ex.gz"))

bzfile(description, open = "", encoding = getOption("encoding"), compression = 9)
con <- bzfile("women8", "w")
print(readLines(zz <- bzfile("ex.bz2")))

xzfile(description, open = "", encoding = getOption("encoding"), compression = 6)

unz(description, filename, open = "", encoding = getOption("encoding"))

pipe(description, open = "", encoding = getOption("encoding"))
readLines(pipe("ls -1"))
scan(pipe("sed -e s/,$// data2_"), sep = ",")

fifo(description, open = "", blocking = FALSE, encoding = getOption("encoding"))
zz <- fifo("foo-fifo", "w+")

flush(con)

isOpen(con, rw = "")
c(isOpen(Tfile, "r"), isOpen(Tfile, "w"))
isIncomplete(con)

file.show("all.Rout")
file.show("outfile", delete.file = TRUE)

dput(x, file = "", control = c("keepNA", "keepInteger", "showAttributes"))
dput(bazi)
dput(mean, "foo")
dput(list6, control = "useSource")
dput(xx, control = "digits17")
dput(number_list, "foo", control = "hexNumeric");

dget(file, keep.source = FALSE)
bar <- dget("filename")

dump()
dump(c("x", "y"), file="/R/dumpfile.rtf")

save(..., list = character(), file = stop("'file' must be specified"), ascii = FALSE, version = NULL, envir = parent.frame(), compress = isTRUE(!ascii), compression_level, eval.promises = TRUE, precheck = TRUE)
save(myObj, file = con)
save(xx, list, file = "xzlist.RData")
save.image(file = ".RData", version = NULL, ascii = FALSE, compress = !ascii, safe = TRUE)
save.image()

load(file="/data/test.RData")

read.csv(file, header = TRUE, sep = ",", quote = "\"", dec = ".", fill = TRUE, comment.char = "", …)
read.csv2(file, header = TRUE, sep = ";", quote = "\"", dec = ",", fill = TRUE, comment.char = "", …)
team_from_csv <- read.csv("myfile.csv")
bank <- read.csv("bank.csv", stringsAsFactors = F)
df <- read.csv(path, stringsAsFactors = FALSE)
read.csv(tf, fill = TRUE)
read.csv(tf, fill = TRUE, header = FALSE, col.names = paste0("V", seq_len(ncol)))
wines <- read.csv('https://goo.gl/KfalMv')
read.csv2("Exercise6.2.csv",na.strings="",skip=2)[,-1]
mydata <- read.csv2("data.csv", header=T)

write.csv(…)
write.csv(x, file = "foo.csv", row.names = FALSE)
write.csv(x, file = "foo.csv", fileEncoding = "UTF-16LE")
write.csv2(…) # sep=";", dec=","
write.csv2(my.data,"Data/Exercise2.csv")

read.delim(file, header = TRUE, sep = "\t", quote = "\"", dec = ".", fill = TRUE, comment.char = "", …)
read.delim2(file, header = TRUE, sep = "\t", quote = "\"", dec = ",", fill = TRUE, comment.char = "", …)
hotdogs <- read.delim("hotdogs.txt", header = FALSE, col.names = c("type", "calories","sodium"), sep="\t")
hotdogs2 <- read.delim("hotdogs.txt", header = FALSE, col.names = c("type", "calories", "sodium"), colClasses = c("factor", "NULL", "numeric"))
tmp <- read.delim(file.path(R.home("share"), "zoneinfo", "zone.tab"), header = FALSE, comment.char = "#", col.names = cols)

read.table(file, header = FALSE, sep = "", quote = "\"'", dec = ".", numerals = c("allow.loss", "warn.loss", "no.loss"), row.names, col.names, as.is = !stringsAsFactors, na.strings = "NA", colClasses = NA, nrows = -1, skip = 0, check.names = TRUE, fill = !blank.lines.skip, strip.white = FALSE, blank.lines.skip = TRUE, comment.char = "#", allowEscapes = FALSE, flush = FALSE, stringsAsFactors = default.stringsAsFactors(), fileEncoding = "", encoding = "unknown", text, skipNul = FALSE)
team_from_text_file<- read.table("myfile.txt")
read.table("states.txt", header=TRUE, sep="/", stringsAsFactors=FALSE)
hotdogs <- read.table(path,  sep = "\t", col.names = c("type", "calories", "sodium"))
cran_mirrors <- read.table(cran_mirrors_file, header = TRUE, sep = ",", quote = '"', dec = ".", fill = TRUE, comment.char = "")
df <- read.table("data/data6.dat", skip=2, header=T, comment.char="--", nrows=100, na.strings=".")
read.table("foo.csv", header = TRUE, sep = ",", row.names = 1)
df <- read.table("http://www.satya.com/.../data.csv", header = TRUE, sep = ",")
read.table(header = TRUE, text = "
a b
1 2
3 4
")

write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ", eol = "\n", na = "NA", dec = ".", row.names = TRUE, col.names = TRUE, qmethod = c("escape", "double"), fileEncoding = "")

write.table(x, file = "foo.csv", sep = ",", col.names = NA, qmethod = "double")
write.table(df, file="/data/filename.dat", row.names=FALSE, col.names=TRUE, sep=",")
write.table(matrix9,"Data/Exercise6.txt", row.names=FALSE, col.names=FALSE, append=T)
write.table(mydat,file="mydat.csv",quote=T,append=F,sep=",",eol = "\n", na = "NA", dec = ".", row.names = T,col.names = T)

read.fwf() # fixed width format
write.fwf()

download.file("https://goo.gl/fjA0", destfile = "pdata.csv", quiet = TRUE)

install.packages("gdata")
read.xls(xls, sheet=1, verbose=FALSE, pattern, na.strings=c("NA","#DIV/0!"), ..., method=c("csv","tsv","tab"), perl="perl")
xls2csv(xls, sheet=1, verbose=FALSE, blank.lines.skip=TRUE, ..., perl="perl")
xls2tab(xls, sheet=1, verbose=FALSE, blank.lines.skip=TRUE, ..., perl="perl")
xls2tsv(xls, sheet=1, verbose=FALSE, blank.lines.skip=TRUE, ..., perl="perl")
xls2sep(xls, sheet=1, verbose=FALSE, blank.lines.skip=TRUE, ..., method=c("csv","tsv","tab"), perl="perl")
iris <- read.xls(xlsfile)
iris <- read.xls(xlsfile, method="tab")
iris <- read.xls(xlsfile, perl="C:/perl/bin/perl.exe")
nba <- read.xls("http://mgtclass.mgt.unm.edu/Bose/Excel/Tutorial.05/Cases/NBA.xls")
crime <- read.xls(crime.url, pattern = "State")
data <- read.xls(exampleFile, sheet="Sheet Second",v=TRUE)

library(foreign)
mydata <- read.dta("mydata.dta",convert.dates = TRUE, convert.factors = TRUE, convert.underscore = TRUE)
write.dta(mydata, file = "mydata.dta")
mydata<-read.xport("SASData.xpt")
mydata<-read.spss("SPSSData.sav")
df  <- read.dbf("file.dbf")

library(speedR)
speedR()
df <- speedR.importany(file = "file.ods")

library("ff") # For large CSV files
df <- read.csv.ffdf(file="large_file.csv", header=TRUE, VERBOSE=TRUE, first.rows=10000, next.rows=50000)

require("XLConnect")
wb <- loadWorkbook("myfile.xls", create = FALSE)
df1 <- readWorksheet(wb, sheet = "mysheet")
df2 <- readNamedRegion(wb, name = "myname", header = TRUE)
createSheet(wb, name = "mtcars")
createName(wb, name = "mtcars", formula = "mtcars!$B$4")
appendWorksheet(wb, mtcars, sheet = "mtcars")
saveWorkbook(wb)

library(xlsReadWrite)
xls.getshlib()
mydat <- read.xls("myfile.xls", colNames = T, sheet = "mysheet", type = "data.frame", from = 1, checkNames = TRUE)
df = read.xls("myfile.xls", sheet = 1)
df <- read.xls("iris.xls", sheet=1, perl="C:/Perl/bin/perl.exe")

library("readxl")
file1 <- read_xls("dataset.xls", Sheet=2)
sheet_df <- read_excel("Media data information.xlsx", sheet = "Media Investment")

library("gnumeric")
df1 <- read.gnumeric.sheet(file = "df.xls", head = TRUE, sheet.name = "DDS")
df2 <- read.gnumeric.sheet(file = "df.xlsx", head = TRUE, sheet.name = "DDA")
df <- read.gnumeric.sheets(file = "df.gnumeric", head = TRUE)

require(RCurl)
myCsv <- getURL("https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AkuKBh0jM2TppUFFxcdoUlCQJh2&single=true&gid=0&output=csv")
read.csv(textConnection(myCsv))

library("readODS")
df=read.ods("df.ods")

library("ROpenOffice")
df <- read.ods(file = "df.ods")

library("rjson")
df <- fromJSON(paste(readLines("json.txt"), collapse=""))
json <- toJSON(df)

path <- file.path("~", "datasets", "states.csv")
path <- file.path("data", "hotdogs.txt")
list.files(path = ".", pattern = NULL, all.files = FALSE, full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE) dir(path = ".", pattern = NULL, all.files = FALSE, full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
list.files()
list.files(R.home())
list.dirs(path = ".", full.names = TRUE, recursive = TRUE)
list.dirs(R.home("doc"), full.names = FALSE)
cran_mirrors_file <- R.home("doc/mirrors.csv")
unlink(tf)
getwd()
(WD <- getwd())
setwd(dir)

library(feather)
mtcars2 <- read_feather(feather_example("mtcars.feather"))
write_feather(x, path)

library(readr)
cols(a = "i")
cols_only(a = col_integer())
cols_condense(s)
date_names_lang("ko")
guess_encoding(read_lines_raw(readr_example("mtcars.csv")))
locale("es", decimal_mark = ",")
parse_character(x, na = c("", "NA"), locale = default_locale())
guess_encoding("companies.txt")
read_delim(file, delim, quote = "\"", escape_backslash = FALSE, escape_double = TRUE, col_names = TRUE, col_types = NULL, locale = default_locale(), na = c("", "NA"), quoted_na = TRUE, comment = "", trim_ws = FALSE, skip = 0, n_max = Inf, guess_max = min(1000, n_max), progress = show_progress())
read_delim("a|b\n1.0|2.0", delim = "|")
read_csv(file, col_names = TRUE, col_types = NULL, locale = default_locale(), na = c("", "NA"), quoted_na = TRUE, quote = "\"", comment = "", trim_ws = TRUE, skip = 0, n_max = Inf, guess_max = min(1000, n_max), progress = show_progress())
Data <- read_csv("Letter-recognition.csv")
read_csv(readr_example("mtcars.csv.zip"))
read_csv("https://github.com/tidyverse/readr/raw/master/inst/extdata/mtcars.csv")
read_csv("x,y\n1,2\n3,4", col_types = "dc")
read_csv("x,y\n1,2\n3,4", col_types = list(col_double(), col_character()))
read_csv2(file, col_names = TRUE, col_types = NULL, locale = default_locale(), na = c("", "NA"), quoted_na = TRUE, quote = "\"", comment = "", trim_ws = TRUE, skip = 0, n_max = Inf, guess_max = min(1000, n_max), progress = show_progress())
read_csv2("a;b\n1,0;2,0")
read_tsv(file, col_names = TRUE, col_types = NULL, locale = default_locale(), na = c("", "NA"), quoted_na = TRUE, quote = "\"", comment = "", trim_ws = TRUE, skip = 0, n_max = Inf, guess_max = min(1000, n_max), progress = show_progress())
read_tsv("a\tb\n1.0\t2.0")

library(jsonlite)
myjson <- toJSON(cars)
jsoncars <- toJSON(mtcars, pretty=TRUE)
fromJSON("http://www.omdbapi.com/?t=Pulp+fiction&y=&plot=short&r=json")
fromJSON('{"city" : "Z\\u00FCrich"}')
cat(myjson)
prettify(myjson)
minify(myjson)
write_json(iris, tmp)
read_json(tmp, simplifyVector = TRUE)
jsoncars <- serializeJSON(mtcars)
mtcars2 <- unserializeJSON(jsoncars)

Related aRticles:  R Matrices     R dplyr package


2 comments:

  1. Thanks for helping out, fantastic information.

    ReplyDelete
  2. Its good as your other posts :D, regards for posting.

    ReplyDelete