RR语言知识干货

R语言与生信应用15-R语法-R文件操作3

2019-05-02  本文已影响63人  BioSi

R文件操作3

文本格式


dput操作R对象

通过dput函数将R对象写入文件,使用dget函数将文件读入R。

> 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

dump函数操作R对象

dump函数可以同时打包多个R对象写入文件,可以使用source函数将文件读回R。

> 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"

其他数据操作的函数

数据操作可以通过创建一个链接(其他语言称为文件句柄)来实现。


文件链接

> str(file)
function (description = "", open = "", blocking = TRUE,
          encoding = getOption("encoding"))

文件链接可以帮助用户更灵活地操作文件或外部对象,我们不用直接对该链接进行操作,R中的函数可以直接处理。

con <- file("foo.txt", "r")
data <- read.csv(con)
close(con)

等同于

data <- read.csv("foo.txt")

按行读取文件

> con <- gzfile("words.gz") 
> x <- readLines(con, 10) 
> x
 [1] "1080"     "10-point" "10th"     "11-point"
 [5] "12-point" "16-point" "18-point" "1st"
 [9] "2"        "20-point"

writeLines读取字符串向量,将向量中每行对象按行写入文件。


readLines在读取网页数据十分有用

> con <- url("http://www.baidu.com", "r")
> x <- readLines(con)
> head(x)
[1] "<!DOCTYPE html>"  "<!--STATUS OK-->" ""                 ""                
[5] ""  

课程分享
生信技能树全球公益巡讲
https://mp.weixin.qq.com/s/E9ykuIbc-2Ja9HOY0bn_6g
B站公益74小时生信工程师教学视频合辑
https://mp.weixin.qq.com/s/IyFK7l_WBAiUgqQi8O7Hxw
招学徒:
https://mp.weixin.qq.com/s/KgbilzXnFjbKKunuw7NVfw

上一篇 下一篇

猜你喜欢

热点阅读