R Programming week1-Reading Data
Reading Data
There are a few principal functions reading data into R.
read.table, read.csv, for reading tabular data
readLines, for reading lines of a text file
source, for reading in R code files (inverse of dump)
dget, for reading in R code files (inverse of dput)
load, for reading in saved workspaces
unserialize, for reading single R objects in binary form
Writing Data
There are analogous functions for writing data to files
write.table
writeLines
dump
dput
save
serialize
Reading Data Files with read.table
The read.table function is one of the most commonly used functions for reading data. It has a few important arguments:
file, the name of a file, or a connection
header, logical indicating if the file has a header line
sep, a string indicating how the columns are separated
colClasses, a character vector indicating the class of each column in the dataset
nrows, the number of rows in the dataset
comment.char, a character string indicating the comment character s
kip, the number of lines to skip from the beginning
stringsAsFactors, should character variables be coded as factors?
read.table
For small to moderately sized datasets, you can usually call read.table without specifying any other arguments
data <- read.table("foo.txt")
R will automatically
skip lines that begin with a #
figure out how many rows there are (and how much memory needs to be allocated)
figure what type of variable is in each column of the table Telling R all these things directly makes R run faster and more efficiently.
read.csv is identical to read.table except that the default separator is a comma.
Reading in Larger Datasets with read.table
With much larger datasets, doing the following things will make your life easier and will prevent R from choking.
Read the help page for read.table, which contains many hints
Make a rough calculation of the memory required to store your dataset. If the dataset is larger than the amount of RAM on your computer, you can probably stop right here.
Set comment.char = "" if there are no commented lines in your file.
Use the colClasses argument. Specifying this option instead of using the default can make ’read.table’ run MUCH faster, often twice as fast. In order to use this option, you have to know the class of each column in your data frame. If all of the columns are “numeric”, for example, then you can just set colClasses = "numeric". A quick an dirty way to figure out the classes of each column is the following:
initial <- read.table("datatable.txt", nrows = 100)
classes <- sapply(initial, class)
tabAll <- read.table("datatable.txt", colClasses = classes)
Set nrows. This doesn’t make R run faster but it helps with memory usage. A mild overestimate is okay. You can use the Unix tool wc to calculate the number of lines in a file.
Know Thy System
In general, when using R with larger datasets, it’s useful to know a few things about your system.
How much memory is available?
What other applications are in use?
Are there other users logged into the same system?
What operating system? Is the OS 32 or 64 bit?
Calculating Memory Requirements
Calculating Memory Requirements I have a data frame with 1,500,000 rows and 120 columns, all of which are numeric data. Roughly, how much memory is required to store this data frame? 1,500,000 × 120 × 8 bytes/numeric = 1440000000 bytes = 1440000000 / bytes/MB = 1,373.29 MB = 1.34 GB
Textual Formats
dumping and dputing are useful because the resulting textual format is edit-able, and in the case of corruption, potentially recoverable.
Unlike writing out a table or csv file, dump and dput preserve the metadata (sacrificing some readability), so that another user doesn’t have to specify it all over again.
Textual formats can work much better with version control programs like subversion or git which can only track changes meaningfully in text files
Textual formats can be longer-lived; if there is corruption somewhere in the file, it can be easier to fix the problem
Textual formats adhere to the “Unix philosophy”
Downside: The format is not very space-efficient
dput-ting R Objects
Another way to pass data around is by deparsing the R object with dput and reading it back in using dget.
> y <- data.frame(a = 1, b = "a")
> dput(y) structure(list(a = 1, b = structure(1L, .Label = "a", class = "factor")), .Names = c("a", "b"), row.names = c(NA, -1L), class = "data.frame")
> dput(y, file = "y.R")
> new.y <- dget("y.R")
> new.y
a b
1 1 a
Dumping R Objects
Multiple objects can be deparsed using the dump function and read back in using source
> x <- "foo"
> y <- data.frame(a = 1, b = "a")
> dump(c("x", "y"), file = "data.R")
> rm(x, y)
> source("data.R")
> y
a b
1 1 a
> x
[1] "foo"
Interfaces to the Outside World
Data are read in using connection interfaces. Connections can be made to files (most common) or to other more exotic things.
file, opens a connection to a file
gzfile, opens a connection to a file compressed with gzip
bzfile, opens a connection to a file compressed with bzip2
url, opens a connection to a webpage
File Connections
> str(file) function (description = "", open = "", blocking = TRUE, encoding = getOption("encoding"))
description is the name of the file
open is a code indicating
“r” read only
“w” writing (and initializing a new file)
“a” appending
“rb”, “wb”, “ab” reading, writing, or appending in binary mode (Windows)
Connections
In general, connections are powerful tools that let you navigate files or other external objects. In practice, we often don’t need to deal with the connection interface directly.
con <- file("foo.txt", "r")
data <- read.csv(con)
close(con)
is the same as
data <- read.csv("foo.txt")
R Programming week1-Reading Data的更多相关文章
- Coursera系列-R Programming第二周
博客总目录,记录学习R与数据分析的一切:http://www.cnblogs.com/weibaar/p/4507801.html --- 好久没发博客 且容我大吼一句 终于做完这周R Progra ...
- Coursera系列-R Programming第三周-词法作用域
完成R Programming第三周 这周作业有点绕,更多地是通过一个缓存逆矩阵的案例,向我们示范[词法作用域 Lexical Scopping]的功效.但是作业里给出的函数有点绕口,花费了我们蛮多心 ...
- 让reddit/r/programming炸锅的一个帖子,还是挺有意思的
这是原帖 http://www.reddit.com/r/programming/comments/358tnp/five_programming_problems_every_software_en ...
- 【MySQL】MySQL同步报错-> Last_IO_Error: Got fatal error 1236 from master when reading data from binary log
这个报错网上搜索了一下,大部分是由于MySQL意外关闭或强制重启造成的binlog文件事务点读取异常造成的主从同步报错 Last_IO_Error: Got fatal error 1236 from ...
- mysql 主从 Got fatal error 1236 from master when reading data from binary log: 'Could not find first 错误
本地MySQL环境,是两台MySQL做M-M复制.今天发现错误信息: mysql 5.5.28-log> show slave status\G ************************ ...
- Last_IO_Errno: 1236 Last_IO_Error: Got fatal error 1236 from master when reading data from binary lo
mysql> show slave status\G *************************** 1. row *************************** ...
- SQL data reader reading data performance test
/*Author: Jiangong SUN*/ As I've manipulated a lot of data using SQL data reader in recent project. ...
- R语言数据分析利器data.table包 —— 数据框结构处理精讲
R语言data.table包是自带包data.frame的升级版,用于数据框格式数据的处理,最大的特点快.包括两个方面,一方面是写的快,代码简洁,只要一行命令就可以完成诸多任务,另一方面是处理 ...
- OpenTSDB-Querying or Reading Data
Querying or Reading Data OpenTSDB offers a number of means to extract data such as CLI tools, an HTT ...
随机推荐
- eclipse中经常使用快捷键
熟练一些快捷键,会使你的开发更加快捷.高效,值得花些时间学一下! 1. ctrl+shift+r:打开资源 这可能是全部快捷键组合中最省时间的了.这组快捷键能够让你打开你的工作区中不论什么一个文件,而 ...
- 百度AI的语音合成,语音识别
1,语音的合成,识别 后端代码: from aip import AipSpeech, AipNlp import os # 语音合成 """ 你的 APPID AK S ...
- 相关性系数缺点与证明 k阶矩
相关性系数 https://baike.baidu.com/item/相关系数/3109424?fr=aladdin 缺点 需要指出的是,相关系数有一个明显的缺点,即它接近于1的程度与数据组数n相关, ...
- Delphi全角转半角
function ToDBC( input :String):WideString;varc:WideString;i:Integer;beginc := input;for i:=1 to Leng ...
- CentOS 7.2更改网卡名称
背景 没啥背景,就是VMWare装的CentOS虚拟机的自带网卡名有点乱,想重新定义一下. 环境 1.VMWare虚拟机 6张网卡 2.系统 [root@localhost ~]# cat /etc/ ...
- HDU - 2586 How far away ?(离线Tarjan算法)
1.给定一棵树,每条边都有一定的权值,q次询问,每次询问某两点间的距离. 2.这样就可以用LCA来解,首先找到u, v 两点的lca,然后计算一下距离值就可以了. 这里的计算方法是,记下根结点到任意一 ...
- java 类属性、方法加载的顺序
1.静态变量 2.静态代码块 3.局部代码块 4.构造函数 5.普通代码块 6.静态方法 7.普通方法 8.普通属性
- BZOJ4814,几何
对每个关键点i,将每个三角形缩成一个线段(因为三角形不相交),然后把线段两端点 和其他关键点一起 以i为中心点 极角排序. 扫一圈.扫到一个关键点j时, 判断当前最靠近i的线段是否遮盖i到j的路径, ...
- python调用window dll和linux so例子
#!/usr/bin/python# -*- coding: UTF-8 -*-#python dll.pyimport win32api# 打开记事本程序,在后台运行,即显示记事本程序的窗口win3 ...
- 视音频编解码基本术语及解释&MediaInfo
MEDIA INFO 下载: https://mediaarea.net/en/MediaInfo/Download/Windows 摘要: 整理了一些基本视音频术语,用于入门和查询 ...