首页 > > > R语言笔记2:读写数据所需的主要函数、与外部环境交互
作者:圈圈
来源公众号:宏基因组

Getting Data In and Out of R
(一)读取数据
读取数据所需的几种函数:
read.table、 read.csv:最常用的读取列表数据函数,可返回数据框形式。readLines:逐行读取文本文件,返回一个字符向量source:读取R代码、脚本dget:读取R代码(读取的是以逆句法分析后以文本文件储存的R对象)load、 unserialize:把二进制对象读入Rread.table()参数:
file:文件名(字符串,即文件路径)header:逻辑标志,表明第一行是否有表头、行名(是变量名还是数据)sep:分隔符(字符串,表明每一列是怎么分隔的,可能是逗号、冒号、空格等)colClasses:字符向量(长度=数据集列数)说明数据集中每一列数据的类别nrows:数据集中数据的行数comment.char:字符串(用于表明文件中注释的字符)skip:指定文件(非数据区域)从上到下多少行可忽略stringsAsFactors:选择是否把文字变量编码为因子,默认为TRUE将文件存至Rstudio识别的路径
在 read.table()函数中填写文件名之前,需要将文件存到正确的路径中
例如:
> ## 查看保存路径> getwd()[1] "d:/Program Files/RStudio"> ## 修改保存路径> setwd("E:/read data")> ## 读取文件> read.csv(data.csv, TRUE)>> ## 运行文件> data <- read.csv("data.csv", header = FALSE)> data
读取中小型数据集时
直接写文件名
> data <- read.table("foo.txt")
读取大型数据集时
你需要先清楚该数据占多大内存,如果不设置其他参数,R会默认将整个数据集都载入内存中。
comment.char 设置为空,即 comment.char=""
colClasses 参数很重要,如果不设置,R会扫描每一列数据并判断其类型,非常耗费时间。colClasses=numeric
nrow()参数,如下initial <- read.table("datatable.txt", nrows = 100) #先读前100行classes <- sapply (initial, class) #sapply()遍历每一列,调用class函数告诉你每一列的数据类型,然后将这些信息储存在classes中,tabALL <- read.table("datatable.txt", colClasses = classes) #读取整个数据时,使用classes中的信息来指定colClasses)
(二)写入数据
与读取数据所用函数相对应的写入数据函数:
write.table、 write.csv
writeLinesdumpdputsave、 serialize
(三)输出函数dump()和 dput()是两种重要的输出函数,用于储存格式和数据。
它们可以包含更多元的数据,属于文本格式但是和表格形式有所不同。如果你对数据框使用 dump()和 dput() 函数,输出结果包括数据框每一列的数据类型,这样读取的是后就不用再次指定类别了。source和 dget函数可以读取未经 dump()和 dput() 输出的数据
dput()dput() 可以生成一些代码,这些代码可用于重建R对象:
> ## Create a data frame> y <- data.frame(a = 1, b = "a") > ## Print 'dput' output to console> 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")
输出也可以直接保存到文件中,然后通过 dget() 读取:
> ## Send 'dput' output to a file> dput(y, file = "y.R") > ## Read in 'dput' output from a file> new.y <- dget("y.R") > new.y a b1 1 a
dump()dump()函数和 dget()类似,区别是后者只能对单一R对象使用,而 dump() 可作用于多个R对象,接受的是一个包含对象名字的字符向量。
> ##创建两个对象x和y> x <- "foo"> y <- data.frame(a = 1L, b = "a")> ## 传递dump参数,包含对象的名字,以及另一个文件名,即将这些对象储存在这个文件中> dump(c("x", "y"), file = "data.R") > ##删除两个对象> rm(x, y)> ##对储存对象调用source函数> source("data.R")> ##重建x, y> str(y)'data.frame': 1 obs. of 2 variables: $ a: int 1 $ b: Factor w/ 1 level "a": 1> x[1] "foo"
(四)与外部环境交互
R通过一些主要函数与外界交互,建立联系。
最常见的联系是与文件建立关联。如 file() 读取文本文件 、 gzfile() 和 bzfile()读取压缩文件等。 url() 可用于与网页建立联系。
联系交互背后的思想是它提炼出与不同类型的R外部对象建立联系的机制。
file函数的几种参数
其中,description是文件名,open参数需要一个标识,包括r(读取,reading),w(写入,writing),a(附加,appending),rb、wb和ab分别表示读取、写入和附加二进制文件。
> str(file)function (description = "", open = "", blocking = TRUE, encoding = getOption("encoding"), raw = FALSE, method = getOption("url.method", "default"))
举例,查看名为"foo.txt"的csv.文件
> ## Create a connection to 'foo.txt'> con <- file("foo.txt") > > ## Open connection to 'foo.txt' in read-only mode> open(con, "r") > > ## Read from the connection> data <- read.csv(con) > > ## Close the connection> close(con)
以上三行命令和直接使用read.csv函数的效果一样,因此建立联系的必要性不大
> data <- read.csv("foo.txt")
但是当你只想读取文件的一部分的话,联系是有必要的。例如,建立联系后,使用readLines函数读取文件前10行:
> ## Open connection to gz-compressed text file> con <- gzfile("words.gz") > x <- readLines(con, 10) > x [1] "1080" "10-point" "10th" "11-point" "12-point" "16-point" [7] "18-point" "1st" "2" "20-point"
读取网页数据
首先使用 url() 函数与网页建立联系。然后通过readLines函数来读取文本。这是除了 read.table() 和 read.csv()之外用来读取数据的另外一种方式。
> ## Open a URL connection for reading> con <- url("http://www.jhsph.edu", "r") > > ## Read the web page> x <- readLines(con) > > ## Print out the first few lines> head(x) [1] "<!DOCTYPE html>" [2] "<html lang=\"en\">" [3] "" [4] "<head>" [5] "<meta charset=\"utf-8\" />" [6] "<title>Johns Hopkins Bloomberg School of Public Health</title>"
参考资料:
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31537575/viewspace-3163778/ ,如需转载,请注明出处,否则将追究法律责任。