R命令实录

读取dataframe的指定行或列

http://shichangshun.cn/2015/11/09/%E6%8A%80%E6%9C%AF/2015-11-09-Read-rows-col/

1
2
3
4
5
6
7
if(!file.exists("read")){
dir.create("read")
}# 创建工作路径文件夹
setwd("./read") # 设置工作路径
if(!file.exists("data")){
dir.create("data")
} # 新建data文件夹

命令的重复

1
var.genes=Reduce(intersect, var.genes1)

快速计算cor

library(HiClimR)
fastCor

数据框替换值

method1: 使用封装函数
1
2
3
4
5
6
7
8
9
10
11
currentid
newid
pbmc$ident<- plyr::mapvalues(pbmc$ident,from=currentid,to=newid)
##### method2: 使用gsub
anno$celltype <- anno$cluster_new
anno$celltype <- paste0("_",paste0(anno$celltype,'_'))
ma$cluster <- paste0("_",paste0(ma$cluster,"_"))
for (i in unique(ma$cluster)) {
anno$celltype <- gsub(anno$celltype,pattern = i,replacement = ma$V2[i])
print(i)
}
method3: 使用%>%

trimws

替换开头或结尾的空格、换行符、制表符、回车。

1
trimws(gene,which=c("both"), whitespace="[ \t\r\n]")

scale

1
2
library(scales)
rss_ct_scale<-apply(rss_ct, 1, rescale,to=c(-2,2))

ggplot 多个画板一个图

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
######################################  same mouse
library(gridExtra)
library(ggplot2)
plot_correlation <- function(i){
name1 <- paste0('T',paste0(i,"human"))
name2 <- paste0('T',paste0(i+1,"human"))
p<-ggplot(ave_teratoma, aes(x=get(name1), y=get(name2))) +
geom_point(alpha=1, size=1) +
geom_smooth(method="lm") +
theme_bw() +
xlab(name1)+ylab(name2)+
ggtitle(paste0("Mouse",i/2-3))+
theme(text = element_text(size=10), legend.title=element_blank(),plot.title = element_text(hjust = 0.5))+
stat_fit_glance(method = 'lm',

method.args = list(formula = y ~ x),

mapping = aes(label = sprintf('R^2~"="~%.3f~~italic(P)~"="~%.2g', stat(r.squared), stat(p.value))),

parse = TRUE,label.x = 0.95,label.y = 0.95)
}

plot_list <- lapply(seq(8,18,2), plot_correlation)
n <- length(plot_list)
nCol <- floor(sqrt(n))
grid.arrange(grobs = plot_list, ncol = nCol) ## display plot
ggsave(file = "same_mouse_correlation.png", arrangeGrob(grobs = plot_list, ncol = 2),height = 9,width = 6) ## save plot