1. 下载文件
有一个包叫downloader,使用这个包的函数 download可以正确下载文件,而且,download和download.file参数是一致。
install.packages("downloader")
library(downloader)
furl <-"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
download(url=furl,destfile="./asc.csv")
2. rvest包网络数据抓取示例:安徽各市区PM2.5监测站数量
library(rvest)
url ="http://www.aepb.gov.cn/Pages/Aepb14_SJZX.aspx"
anhui = url %>% html() %>%html_nodes("table") %>% .[[10]] %>% html_table()
city = anhui[1]
a = url %>% html() %>%html_nodes("table tbody a") %>% html_attrs()
a = as.character(a)
b =paste("http://www.aepb.gov.cn/Pages/",a,sep = "")
myfun = function(x) b[x] %>% html() %>%html_nodes("table") %>% .[[10]] %>% html_table(fill = T) %>%nrow()
site = sapply(1:length(b),myfun)
data = data.frame(城市 = city,监测站数量 =site)
data
城市监测站数量
1 合肥 10
2 淮北 3
3 亳州 2
4 宿州 3
5 蚌埠 6
6 阜阳 3
7 淮南 6
8 滁州 3
9 六安 4
10 马鞍山 5
11 芜湖 4
12 宣城 3
13 铜陵 6
14 池州 3
15 安庆 4
16 黄山 3
3. 在坐标轴上显示百分比
x=1:10
y=1:10
plot(x,y,axes=F)
z=numeric(length(y))
z[1]=y[1]
for(i in 2:length(y))
z[i]=(z[i-1]+y[i])
z=z/sum(y)
z=z*100
f=round(z);
f
axis(1)
axis(2,1:length(y),paste(f,'%',sep=''))
box()
4. 字符串格式化函数sprintf()
函数使用方法与C语言相同
> sprintf("%f", pi)
[1] "3.141593"
> sprintf("%.3f", pi)
[1] "3.142"
> sprintf("%1.0f", pi)
[1] "3"
> sprintf("%5.1f", pi)
[1] " 3.1"
> sprintf("%05.1f", pi)
[1] "003.1"
> sprintf("%+f", pi)
[1] "+3.141593"
> sprintf("% f", pi)
[1] " 3.141593"
> sprintf("%-10f", pi) # leftjustified
[1] "3.141593 "
> sprintf("%e", pi)
[1] "3.141593e+00"
> sprintf("%E", pi)
[1] "3.141593E+00"
> sprintf("%g", pi)
[1] "3.14159"
> sprintf("%g", 1e6 * pi) # -> exponential
[1] "3.14159e+06"
> sprintf("%.9g", 1e6 * pi) #-> "fixed"
[1] "3141592.65"
> sprintf("%G", 1e-6 * pi)
[1] "3.14159E-06"
5. 抓网页伪装浏览器header
#抓取信息
library(RCurl)
library(XML)
#伪装报头
myheader=c(
"User-Agent"="Mozilla/5.0(Windows;U;WindowsNT 5.1;zh-CN;rv:1.9.1.6",
"Accept"="text/htmal,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language"="en-us",
"Connection"="keep-alive",
"Accept-Charset"="GB2312,utf-8;q=0.7,*;q=0.7"
)
#测试单个url下的信息读取
testurl<-"http://www.fruitday.com/web/product_list/40"
temp<-getURL(testurl,httpheader=myheader,encoding="UTF-8")
k<-htmlParse(temp) #解析网页
write.table(k,"k.txt")
#k
name.node<-getNodeSet(k,'//li[@class="cplist-p02"]/a')
style.node<-getNodeSet(k,'//li[@class="cplist-p03"]')
price.node<-getNodeSet(k,'//li[@class="cplist-p04"]')
name.node
style.node
price.node
#price<-xmlValue(price.node1[[1]])
#price
#name.node
#price<-sapply(getNodeSet(k,'//p[@class="price"]/i/text('),xmlValue)
#url.node1
#name<-xmlGetAttr(url.node[[1]],'title')
#name
#name<-xmlGetAttr(url.node1[[1]],'title')
#name
#getNodeSet(k,'//p[@class="title"]/a[@title]')
price<-c()
style<-c()
name<-c()
for (i in 1:200){
name<-xmlValue(name.node[])
style<-xmlValue(style.node[])
price<-xmlValue(price.node[])
#name<-iconv(name,"UTF-8","gbk")#解决中文正常显示问题
}
name<-iconv(name,"UTF-8","gbk")
df<-data.frame(na=name,sty=style,pr=price)
write.table(df,"tt.txt")
6. 判断文件是否为空
file.info("your_file")$size == 0
7. googleVis包制作地图示例
这是出生儿性别比地图,颜色越深,男婴比例越高,最大的是海南,130:100,最小的是西藏,102:100。这个图是交互式的,鼠标点处停留一下,会显示该省的数据。代码如下:
#用googleVis包的另一种方法,需要能访问google网站,否则无法正常显示
##
provname=c("CN-11","CN-12","CN-13","CN-14","CN-15","CN-21","CN-22","CN-23","CN-31","CN-32","CN-33","CN-34","CN-35","CN-36","CN-37","CN-41","CN-42","CN-43","CN-44","CN-45","CN-46","CN-50","CN-51","CN-52","CN-53","CN-54","CN-61","CN-62","CN-63","CN-64","CN-65");
pop=c(110.56,112.51,113.43,112.52,108.45,112.83,111.23,109.71,110.64,116.51,113.86,127.85,117.93,114.74,112.17,118.46,128.18,126.16,130.30,125.55,135.64,115.13,116.01,107.03,108.71,102.73,122.10,114.82,110.35,108.79,106.12)
##
library(googleVis)
a<-data.frame(provname,pop)
G2 <- gvisGeoChart(a,locationvar='provname',colorvar='pop',options=list(region='CN',displayMode="regions",resolution="provinces",colorAxis="{colors:['yellow','red']}" ))
plot(G2)
省份顺序:
"北京市","天津市","河北省","山西省","内蒙古自治区", "辽宁省","吉林省","黑龙江省","上海市","江苏省", "浙江省","安徽省","福建省","江西省","山东省", "河南省","湖北省","湖南省","广东省", "广西壮族自治区","海南省","重庆市","四川省","贵州省", "云南省","西藏自治区","陕西省","甘肃省","青海省", "宁夏回族自治区","新疆维吾尔自治区"
8. 绘制三维曲面
x <- seq(-10,10, length.out = 50)
y <-x
rotsinc <-function(x,y) {
sinc<- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }
10 *sinc( sqrt(x^2+y^2) )
}
z <- outer(x,y, rotsinc)
persp(x, y, z)
require(rgl)
surface3d(x, y, z)
9. 利用paste函数合并多个字符串
A <- c(1:10)
> A
[1] 1 2 3 4 5 6 7 8 9 10
> A <-as.array(A)
> A
[1] 1 2 3 4 5 6 7 8 9 10
>paste(A,collapse = '')
[1]"12345678910"
10. 矩阵按列排序
>x<-matrix(c(8,3,9,5,7,3),byrow=FALSE,nrow=3)
> x
[,1] [,2]
[1,] 8 5
[2,] 3 7
[3,] 9 3
>x[order(x[,1]),]
[,1] [,2]
[1,] 3 7
[2,] 8 5
[3,] 9 3
11. 命令行方式运行R程序
通过命令行的方式,可以实现多种效果,比如通过批处理程序定时运行R程序。下面是参数列表:
C:\ProgramFiles\R\R-3.1.2\bin\x64>Rcmd
Usage: Rcmdcommand args
where 'command' isone of:
INSTALL Install add-on packages
REMOVE Remove add-on packages
SHLIB Make a DLL for use with dynload
BATCH Run R in batch mode
build Build add-on packages
check Check add-on packages
Rprof Post process R profiling files
Rdconv Convert Rd format to various other formats
Rdiff difference R output files
Rd2pdf Convert Rd format to PDF
Rd2txt Convert Rd format to pretty text
Stangle Extract S/R code from vignette
Sweave Process vignette documentation
config Obtain configuration information about R
open Open a file via Windows file associations
texify Process a latex file
Use Rcmd command--help
for usageinformation for each command.
比如如下调用,可以执行一个R语言脚本:
C:\ProgramFiles\R\R-3.1.2\bin\x64>Rcmd BATCH C:\data\Assign3_Q1.R
12. 3D饼图
library(plotrix) pieval=c(14529,4382,1713,1682,1249,1063,868,9660) pielabels=c("北美云杉","葡萄","蓖麻","毛果杨","小立碗藓","江南卷柏","黑孢块菌","其他") pie3D(pieval,radius=1,labels=paste(pielabels,pieval,paste(round(100*pieval/sum(pieval),2),"%",sep=""),sep="\n"),explode=0.05, labelcex=0.8,height=0.1,main="针叶树比对到UniRef100数据库的物种分布")
|
13. 选择文件夹(文件)以及搜索文件夹
utils::choose.dir | Choose a Folder Interactively |
utils::choose.files | Choose a List of Files Interactively |
list.files(R.home())
## Only filesstarting with a-l or r
## Note that a-lis locale-dependent, but using case-insensitive
## matching makesit unambiguous in English locales
dir("../..",pattern = "^[a-lr]", full.names = TRUE, ignore.case = TRUE)
list.dirs(R.home("doc"))
list.dirs(R.home("doc"),full.names = FALSE)
file.choose() /*chooseonly one file*/
choose.files()/*choose one or more files*/
choose.dir()/*choose one directory*/
若设置以下参数,则可以遍历所有的子文件夹
list.files(recursive=TRUE)
14. mean函数中trim的意义
mean(x, trim =0.1)
就是先把x的最大的10%的数和最小的10%的数去掉,然后剩下的数算平均。
15. melt()函数的作用
melt 是溶解/分解的意思,即拆分数据。
reshape/reshape2 的 melt函数是个 S3通用函数,它会根据数据类型(数据框,数组或列表)选择 melt.data.frame,melt.array或 melt.list函数进行实际操作。
1. 如果是数组(array)类型,melt的用法就很简单,它依次对各维度的名称进行组合将数据进行线性/向量化。如果数组有 n 维,那么得到的结果共有 n+1列,前 n列记录数组的位置信息,最后一列才是观测值。
> datax <-array(1:8, dim=c(2,2,2))
> melt(datax)
Var1Var2 Var3 value
1 1 1 1 1
2 2 1 1 2
3 1 2 1 3
4 2 2 1 4
5 1 1 2 5
6 2 1 2 6
7 1 2 2 7
8 2 2 2 8
> melt(datax,varnames=LETTERS[24:26],value.name="Val")
X Y Z Val
1 1 1 1 1
2 2 1 1 2
3 1 2 1 3
4 2 2 1 4
5 1 1 2 5
6 2 1 2 6
7 1 2 2 7
8 2 2 2 8
2. 如果是列表数据,melt函数将列表中的数据拉成两列,一列记录列表元素的值,另一列记录列表元素的名称;如果列表中的元素是列表,则增加列变量存储元素名称。元素值排列在前,名称在后,越是顶级的列表元素名称越靠后:
> datax <-list(agi="AT1G10000", GO=c("GO:1010","GO:2020"),KEGG=c("0100", "0200", "0300"))
> melt(datax)
value L1
1 AT1G10000 agi
2 GO:1010 GO
3 GO:2020 GO
4 0100 KEGG
5 0200 KEGG
6 0300 KEGG
>melt(list(at_0100=datax))
value L2 L1
1 AT1G10000 agi at_0100
2 GO:1010 GO at_0100
3 GO:2020 GO at_0100
4 0100 KEGG at_0100
5 0200 KEGG at_0100
6 0300 KEGG at_0100
3. 如果数据是数据框类型,melt的参数就稍微复杂些:
> melt(data,id.vars, measure.vars, variable.name = "variable", ..., na.rm =FALSE, value.name = "value")
其中 id.vars是被当做维度的列变量,每个变量在结果中占一列;measure.vars是被当成观测值的列变量,它们的列变量名称和值分别组成 variable和 value两列,列变量名称用variable.name和 value.name来指定。