#R的学习笔记07

2021-02-02  本文已影响0人  ks_c

title: "R的学习笔记05"
author: "ks_c"
date: "2021/2/2"
output: html_document


<font face="宋体">以下为R数据分析指南与速查手册 第三章的内容</font>

导出

导出变量

使用save(..., list = character(),file = stop("'file' must be specified"))可以保存单个变量或一些变量。文件名为.rda或.Rdata。

如果想保存整个环境,用save.image函数。常用用法为save.image(file = ".RData"),用file指定文件名即可。

导出txt或csv

导出为txt格式:

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

导出文件中:

# 数据生成
name <- c("Alice","Bob","Christien","Einstein")
age <- c(10,20,14,25)
gender <- c("F","M","F","M")
weight <- c(25,50,30,54)
nationality <- c("USA","UK","China","German")
height <- c(1.2,1.65,1.43,1.75)
example_df <- data.frame(name,age,gender,weight,nationality,height)

# 保存
write.csv(example_df, file = "example_df.csv")
write.table(example_df, file = "example_df.txt")
write.table(example_df, file = "example_df2.txt",quote = FALSE)#字符串没有引号

导出图片

直接保存而不展示图片:

png("example_plot.png") # 新建一个图片保存格式,png可以是jpg、pdf等
plot(1:10) # 绘图
dev.off() # 关闭图形设备

图片的长、宽、分辨率等参数可参考png等的帮助文档。

如果已经画好了图,可以使用如下代码输出到文件中。

dev.copy(png, 'example_plot2.png')
dev.off()

如果最开始打开的是Windows窗口,则可用savePlot()函数,其用法为:

savePlot(filename="Rplot",
type=c("wmf", "png", "jpeg", "jpg", "bmp", "ps"),
device=dev.cur())

#例子:
windows(width = 9, height = 9, rescale = "fit")  # 打开一个Windows窗口
plot(1:10,type = "l")
savePlot(filename="Myplot",type="pdf")
# savePlot(filename="Myplot",type="png")
## 支持下列格式:"wmf", "emf", "png", "jpg", "jpeg", "bmp", "tif", "tiff", "ps", "eps", "pdf"
dev.off()

导出文本

readr::write_file(txt, file_name.txt", append = FALSE)

writeLines(txt, con = fileConn,sep = "")
close(fileConn)

sink("cat.txt")
操作
sink()

cat(... = ,file = ,sep = ,fill = ,labels = ,append = )

fileConn<-file("writeChar.txt")
writeChar(txt, con = fileConn, eos = NULL, useBytes = FALSE)
close(fileConn)

writeChar

R与python通用的数据

feather

#R中
library(feather)
path <- "my_data.feather"
write_feather(df, path)
df <- read_feather(path)

#py中
import feather
path = 'my_data.feather'
feather.write_dataframe(df, path)
df = feather.read_dataframe(path)

数据载入

数据

read.table默认的分隔符为空格,read.csv2默认的分隔符为分号;
可以改变默认的分隔符。

read.csv(file,
header = TRUE,
sep = ",",
quote = """,
dec = ".",
fill = TRUE,
comment.char = "", ...)

按行或单元导入(表格数据)
按行导入用readLines,按单元导入用scan

文本

整体读取可用readr::read_file,
按行读取可用readLines,如

txt<- read_file("write_file.txt")
上一篇下一篇

猜你喜欢

热点阅读