R语言 指令总结[R instructions]

来源:互联网 发布:皇朝家私 淘宝 编辑:程序博客网 时间:2024/06/03 08:37

说明:个人使用R语言近2年,总结的常用指令。发现写到博客中,方便自己随时随地查看。

          可以保存在txt文档中,使用查找功能进行搜索。不断更新中......

===========================================================================================

1.line()
By using the line()statement instead, you can add new graph elements to an existing graph

============================================================================================
2.均值 mean()
标准差 standard deviation -- sd()
方差 variance -- var()
============================================================================================
3. 连乘 
prod()

============================================================================================
4. 列联函数
table( ) 

============================================================================================
5. 柱状图绘制函数
barplot( ) 

============================================================================================
6.数据集合并
1)
纵向数据合并rbind: row变多了
 【X:100*3, rbind(X,X):200*3】
 
横向数据合并cbind:  col变多了
 【X:100*3, cbind(X,X):100*6】
 
Take a sequence of vector, matrix or data-frame arguments and combine by columns or rows.


2)
merge

============================================================================================  
7. rm
在R软件的使用过程中,工作空间容易很快变得杂乱。rm函数能永久地从工作空间中删除一个或多个对象:
> rm(x)
> rm(x,y,z)
你甚至可以同时删除工作空间中所有的内容。rm函数中有一个list参数,它包含所有需要删除的变量名称。
前面章节介绍过ls函数能返回所有变量名称,因此你可以通过结合rm函数与ls函数,删除工作空间中的所有变量:
> ls()
[1] "f" "x" "y" "z"
> rm(list=ls())
> ls()
character(0)
rm(list=ls())删除对方工作空间中所有的内容

============================================================================================
8.  清空屏幕:
Ctrl+L(or the “Clear console” command under “Edit” menu)

============================================================================================
9. 画频率直方图hist(),概率密度曲线density() 
1)hist(Data$attr , freq=RALSE , density=20, main = "Histogram of Density 0f Data)
### 频率直方图
2)lines(density(Data$attr))
### 直方图中添加概率密度曲线

============================================================================================
10. 集合运算
#首先对集合A,B,C赋值
> A<-1:10
> B<-seq(5,15,2)
> C<-1:5
> #求A和B的 【并集】
> union(A,B)
 [1]  1  2  3  4  5  6  7  8  9 10 11 13 15
> #求A和B的 【交集】
> intersect(A,B)
[1] 5 7 9
> #求【A-B】
> setdiff(A,B)
[1]  1  2  3  4  6  8 10
> #求【B-A】
> setdiff(B,A)  (一维,多维不行)
[1] 11 13 15
> #【检验集合A,B是否相同】
> setequal(A,B)
[1] FALSE
> #【检验元素12是否属于集合C】
> is.element(12,C)
[1] FALSE
> #【检验集合A是否包含C】
> all(C%in%A)
[1] TRUE
> all(C%in%B)
[1] FALSE

===========================================================================================
11.  统计一个向量中有几个0
1. set.seed(2015)
2. x<-sample(0:2,100,replace=T)
3. x
4. sum(x==0)
//sum(x==0)是正确的,因为x==0的运算结果是TURE or FALSE,TRUE代表1,这个相加正好就是为0的个数。
5. #两种运算结果一样,或者
6. length(which(x==0))


============================================================================================
12.  返回数组最大值标号
which.max(x):返回x中最大元素的指标
which.min(x):返回x中最小元素的指标
max(x): 返回x中最大元素
min(x): 返回x中最小元素


    返回矩阵最大元素位置
which(X==max(X),arr.ind=T)

============================================================================================
13.  整除、余数
取整除:%/%
取余数:%%
向下取整floor(7.99999)=7
向上取整ceiling(1.00001)=2
四舍五入round(1.49999)=1
         round(1.5)=2
round(1.50001)=2


============================================================================================
14. 二维空间的2点之间画一条线段
segments(x0, y0, x1 = x0, y1 = y0,
         col = par("fg"), lty = par("lty"), lwd = par("lwd"),
         ...)

============================================================================================ 
15.  csv文件
1)写入csv
(1) write.csv(...)
write.csv(b,"orl.csv",row.names=FALSE) #'b是一个矩阵,写入orl.csv文件
缺点:不能设置col.names=FALSE,即列名为V1,V2,...... 
       如添加了col.names=FALSE,会报错!!!
   
(2)解决方案:write.table() 
参考链接http://r.789695.n4.nabble.com/write-csv-and-col-names-F-td974477.html
write.table(b,"orl.csv",sep=',',row.names=FALSE,col.names=FALSE)
优点:可以设置col.names=FALSE 


【其他例子】
如有2个vector, v1 和 v2
write.table( cbind(v1,v2), paste0( path, "\\llseq.csv"), sep=",", 
             col.names = FALSE, row.names = FALSE, append = FALSE )
#' append=TRUE 覆盖原来的文件


【令】write.table可写入txt文件
如:写入一行文本
write.table("cvxclust_path of X",paste0(dataname,".txt"),row.names=FALSE,col.names=FALSE)
 
2)
读取csv文件:
read.csv( "XX.csv")

============================================================================================
16.  停止正在运行的R程序
按Esc键或点击“停止”(Stop-Sign)图标停止工作。

============================================================================================
17.  write.csv不要输出标题列(第一列)
write.csv(mat,file="filename.csv",row.names=FALSE)
row.names默认为TRUE,设置为FALSE即不输出标题列

============================================================================================ 
18.对向量、矩阵的行或列随机排序
若是向量,sample(x)
matrix/data.frame, x[sample(nrow(x)),] 


sample(x)与sample(x,length(x))等价,即
sample(10)与sample(1:10)及sample(1:10,10)等价

============================================================================================ 
19.sort()/rank()/order()
sort(x,decreasing=FALSE)对向量x排序,返回值 排序后的数值。
                         decreasing=TRUE,逆序
rank(x)             返回值 向量中对应元素的“排名”
order(x)            返回值 对应“排名”的元素所在向量中的位置
 
e.g. 
x<-c(97,93,85,74,32,100,99,67) 


sort(x)
[1] 32 67 74 85 93 97 99 100


rank(x)
[1] 6 5 4 3 1 8 7 2


order(x)
[1] 5 8 4 3 2 1 7 6

============================================================================================
20. 用于管理R工作空间的函数  
1) 改变工作路径
setwd()
     当前工作路径
getwd()


2)     保存空间到文件 (.Rdata) -- 把所有对象都保存
save.image( paste0(dataname,".RData") )
       保存指定对象到一个文件中
save(objectlist,file="myfile")
Eg. save(cc,fc,X,filename="myfile") #cc,fc,X为想要保存的对象


     读取文件内容到当前工作目录(.Rdata)
load( paste0(dataname,".Rdata") )


3)     保存命令历史到文件myfile中(.Rhistory)
        savehistory("myfile")
载入一个命令历史文件(.Rhistory)
      loadhistory("myfile")
  
4)options()
显示或设置当前选项


5)history( # )
显示最近使用过的#个命令(默认值为25)

============================================================================================
21.  安装,加载,卸载包
Install.packages(“clusteval”)
library(clusteval)  require(clusteval)
remove.packages(“clusteval”)

============================================================================================
22.  查看数据类型
class(x)
mode(x)
summary(x)

=============================================================================================
23. 查看系统运行时间的两种方法
【法1】
system.time()
> system.time(apply(icol,1,sampnumberfunction))
用户 系统 流逝
0.16 0.01 0.17


这是计算机操作系统中说明运算时间的概念,
“用户”是消耗在应用程序(非操作系统部分)执行的时间,
“系统”是底层操作系统执行(例如磁盘读写等)部分的时间,
“流逝”是经过的总时间(可以认为是前两者的总和)。
一般优化时主要关注“用户”的时间。


https://cos.name/cn/topic/112434/ 帖子:
时间 |—a——————————————-|
启动 |—b———->|
并行CPU1             |—-c—>|
调用系统底层(比如磁盘读写)      |–d–>|
并行CPU1底层返回后继续执)               |–e–>|
并行CPU2             |—-f—————–>|
并行返回调用并最终结束                          |—g–>|


这里 elapsed 应该就是 a;user 是 b + c + e + f + g;system 是 d。所以在多核情况下,user 是可能超过 elapsed 值的。


【法2】
ptm <- proc.time();ptm
for (i in 1:10000) x <- rnorm(1000)
proc.time()-ptm
===============================================================================================
24.多行注释:
Rstudio: ctrl+shift+C
Sublime_text: ctrl+/

===============================================================================================
25.调试:
【参考】
1. http://blog.csdn.net/u013259893/article/details/41254177
2.《R语言编程艺术》 chapter 13


【指令】
1. debug(f)    从此时起,每次调用f,都会进入debug状态
   undebug(f)  取消f的调试状态
   
   debugonce   只调用一次debug(f)
   
2. f的某行加入browser()   
         ----- 程序执行到此行 浏览器被打开,逐步调试 直至f结束
   
【进入debug状态后】
n/Enter(next): 逐行执行
c  (cintinue): 下次暂停前可能执行若干条语句
where:         栈跟踪路径
Q:             退出browser 

===============================================================================================
26.内存分配
【参考】
http://www.biostatistic.net/thread-3302-1-1.html


【OS】
1. 当前设置下操作系统能分配给R的最大内存
      memory.size(NA)  or  memory.limit()
2. 查看当前R已使用的内存
      memory.size(F)
   查看已分配的内存
  memory.size(T)
3. 扩大分配的内存
      memory.limit(2000)
  
【对象】
1. 查看对象x占用内存的大小
      object.size(x)
2. 对象的存储模式
       storage.mode(x)
通过改变存储模式减少内存占用
3. 使用rm(x),
   如果是非常重要的信息不想删掉,可以存在硬盘里,比如csv文件
4. rm()只会删除变量的引用,不会立即清除占用的内存空间,
   垃圾处理函数gc(),立刻释放空间。
   但通常不必要,因为当内存不够时系统会自动清理垃圾
   
  专门处理大内存对象以及并行处理的包,比如bigmemory等
  
===============================================================================================
27.【安装更新R版本】
【参考】http://blog.leanote.com/post/qiukaino1/R%E8%AF%AD%E8%A8%80%E5%AD%A6%E4%B9%A0-%E5%A6%82%E4%BD%95%E6%9B%B4%E6%96%B0R%EF%BC%9F
  
利用R包进行升级操作(仅适用于Windows)
安装installr包进行升级。代码如下:


install.packages("installr)   ##安装installr软件包
library(installr) ##启用installr软件包

updateR() ##进行升级操作


===============================================================================================
28.【Rstudio中切换R的版本】


 Tools/Global Options/General/R version/Change.../Choose a specific version of R, 
 
 and choose any version you had installed (RStudio will detect any version installed), 
 you can install as many versions as you want and have them in the same R folder inside Program Files
 
===============================================================================================
29.【CRAN】
comprehensive R archive network

===============================================================================================
30.book【R高性能编程】(by Aloysius Lim)
  
===============================================================================================
31.【R 层次聚类--hclust包】
http://blog.csdn.net/sherrymi/article/details/38341185


hclust(d, method = "complete", members=NULL)
d为距离矩阵。
method表示类的合并方法,有:
single            最短距离法
complete        最长距离法
median        中间距离法
mcquitty        相似法
average        类平均法
centroid        重心法
ward            离差平方和法


#'举例
d <- dist(x)
hc <- hclust(d,"single")
plot(hc)


#'然后可以用rect.hclust(tree, k = NULL, which = NULL, x = NULL, h = NULL,border = 2, cluster = NULL)来确定类的个数。 #'tree就是求出来的对象。k为分类的个数,h为类间距离的阈值。border是画出来的颜色,用来分类的。
rect.hclust(hc,k=2)
rect.hclust(hc,h=0.5)


#'提取每个样本所属的类别
label <- cutree(hc,k=2)


===============================================================================================
32.【数据框】
创建数据框:
imgRGB <- data.frame(   
  R = as.vector(img[,,1]),
  G = as.vector(img[,,2]),
  B = as.vector(img[,,3])
  )
  
读取数据框的某列:
imgRGB $ R


数据框的列名:
colnames(imgRGB)

===============================================================================================
33.【读取bmp图片】
#install.packages("bmp")
require(bmp)
a <- read.bmp("D:/R workplace/data/ORL/s1_1.bmp")
 
===============================================================================================
34.【把维度 m*n 的矩阵转成一个 (m*n)*1的矩阵】
dim(a)  -- 112*92
b <- as.matrix( as.vector(a) )  --  10304     1
 
===============================================================================================


===============================================================================================




===============================================================================================




===============================================================================================




===============================================================================================




===============================================================================================




===============================================================================================




===============================================================================================




===============================================================================================




===============================================================================================




===============================================================================================




===============================================================================================




===============================================================================================






===============================================================================================
原创粉丝点击