(更多内容请见:R、ggplot2、shiny 汇总)
1、数据框按照某一列排序:
例如存放学生信息的数据框 rt(name,sex,age,score),按照分数 score 递减排序:
> rt[order(rt[,4],decreasing=T),] ## 特别注意后面的逗号别忘了!
2、小数取整:
> x <- 3.555555
> ceiling(x)
[1] 4
> floor(x)
[1] 3
> trunc(x)
[1] 3
> round(x, digits = 0)
[1] 4
> signif(x, digits = 6)
[1] 3.55556
3、查看某个元素是否在向量里面,用 %in% :
> 34 %in% c(1,2,3,4,34,44)
[1] TRUE
4、求某个日期的前一天:
> as.Date("2015-07-27") - 1
[1] "2015-07-26"
5、输出字符串时要换行,print 中 \n 是无效的,要用 cat :
> print("ABC\nDEF")
[1] "ABC\nDEF"
> cat("ABC\nDEF")
ABC
DEF
6、求数据框的行数:nrow(dt),求数据框的列数:ncol(dt);
求数据框的行标签:rownames(dt),求数据框的列标签:colnames(dt)。
7、把数据框按照某一列的不同值切分成几个数据框,用 split() :
> dt <- data.frame(AA=c(1,2,3), BB=c('a','b','a'))
> dt
AA BB
1 1 a
2 2 b
3 3 a
> group = split(dt, dt$B)
> group
$a
AA BB
1 1 a
3 3 a
$b
AA BB
2 2 b
8、计算程序运行的时间:
> ptm <- proc.time()
> a = 1 + 1 ## 此处放你的程序
> print(proc.time() - ptm)
用户 系统 流逝
0.00 0.00 1.47
9、R程序暂停 n 秒:
Sys.sleep(n) ## 注意此处 n 的单位是秒,不是毫秒
10、直接调用某个包里面的函数:shiny::renderDataTable
11、R语言里面的全局变量:
abc <<- 56 ## 使用'<<-'便可转成全局变量。
## 但在使用的过程中,'<<-'才能改变全局的值,'<-'只能改变局部的值
12、柱状图可能某个柱条为空,去掉空的柱条:加上 factor
> ggplot(data,aes(x = factor(myX), y = myY))
13、查看 ggplot 对象的作图参数:
> p = ggplot(···) + ···
> ggplot_build(p) ## 可查看作图的所有参数,如所有点的坐标、颜色等
14、把 ggplot 对象以图片形式保存到本地:
> p = ggplot(···) + ···
> ggsave("picture1.png", path = "C:/workspace", width = 10, height = 6, dpi = 300)
15、如何将 ggplot2 中的图片标题放在下方(默认在图片正上方):
theme(title = element_text(vjust = -50)) ## 好像没有调相对坐标的参数,只能用绝对坐标来调了
16、(ggplot2 中)去掉背景色:theme(panel.background = element_blank())
17、(ggplot2 中)设置背景色:
theme(panel.background = element_rect(fill = "blue") + ##改变坐标系里面的背景颜色
theme(plot.background = element_rect(fill = "blue", color = "blue") ##改变坐标系之外的背景色
18、雷达图:
library(fmsb)
######## 给数据框加上两行,分别作为蜘蛛图的最大值和最小值
dataframeAdding = function(dataframe){
myMax = c()
myMin = rep(1,ncol(dataframe))
for (i in (1:ncol(dataframe)))
myMax[i] = max(dataframe[,i])
result = rbind(myMax, myMin, dataframe)
return(result)
}
#####主程序开头
dt = data.frame(A = c(321,77,142,270), B = c(290,200,400,100), C = c(24,150,42,75), D = c(122,72,322,12), E = c(450,220,410,300))
result = dataframeAdding(dt) # 画蜘蛛图的要求,数据框的第一行作为图的最大值,第二行作为图的最小值
op <- par(mar = c(1,2,2,1),mfrow = c(2,2)) #用于显示多个图形
radarchart(result,axistype = 0,plwd = 1:5,pcol = 1,title = "(axistype=0, plwd=1:5, pcol=1)")
radarchart(result,axistype = 1,seg = 5,plty = 1,title = "(axistype=1, seg=5, plty=1)")
radarchart(result,axistype = 2,pcol = topo.colors(6),plty = 1,title = "(axistype=2, pcol=topo.colors(6), plty=1)")
radarchart(result,axistype = 3,pty = 32,plty = 1,axislabcol = "grey",na.itp = FALSE,title = "(axistype=3, pty=32, plty=1, axislabcol=\"grey\", na.itp = FALSE)")
par(op)
转载请注明出处,谢谢!(原文链接:http://blog.csdn.net/Bone_ACE/article/details/48326121)