题目来自生信技能树2021生信入门课
1. 使用循环,对iris的1到4列分别画点图(plot)
par(mfrow = c(2,2))
for (i in 1:4){
plot(iris[,i],col = iris[,5])
}

2. 生成一个随机数(rnorm)组成的10行6列的矩阵,列名为sample1,sample2....sample6, 行名为gene1,gene2...gene10,分组为sample1、2、3属于A组,sample4、5、6属于B组。 用循环对每个基因画ggplot2箱线图,并尝试拼图。
- 思路1:
library(reshape2)
library(dplyr)
library(ggplot2)
#生成矩阵
a <- matrix(rnorm(60),nrow = 10,dimnames = list(paste0('gene',1:10),paste0('sample',1:6)))
#转换成长型数据
b= melt(a)
b$group <- rep(c('groupA','groupB'),each=30)
#按group切分生成list并绘图
c <- split(b,b$Var1)
p = list()
for(i in 1:length(c)){
p[[i]]=ggplot(c[[i]],mapping=aes(x=group,y=value,color = group))+geom_boxplot()+
geom_jitter()+theme_light()
}
#拼图
#因为是一个list各一张图,mforw在这里行不通,查了一下patchwork找到了wrap_plots
library(patchwork)
wrap_plots(p,nrow = 2,guides='collect')

#上面是用reshape2的melt做的长宽数值转换,下面是tidyr的尝试
library(tidyr)
b <- as.data.frame(a) #gather函数接受的是data.frame
b$gene <- rownames(a)
b <- gather(b, "sample", "exp", -gene)
b$group <- rep(c('groupA','groupB'),each=30)
head(b)
# gene sample exp group
# 1 gene1 sample1 -0.05044492 groupA
# 2 gene2 sample1 0.05286449 groupA
# 3 gene3 sample1 1.16049768 groupA
# 4 gene4 sample1 0.52962074 groupA
# 5 gene5 sample1 1.12620654 groupA
# 6 gene6 sample1 -0.65658632 groupA
- 思路2:
exp = matrix(rnorm(60),nrow = 10)
colnames(exp) <- paste0("sample",1:6)
rownames(exp) <- paste0("gene",1:10)
exp[1:4,1:4]
#dat = cbind(t(exp),group = rep(c("A","B"),each = 3))
dat = data.frame(t(exp))
dat = mutate(dat,group = rep(c("A","B"),each = 3))
p = list()
library(ggplot2)
for(i in 1:(ncol(dat)-1)){
p[[i]] = ggplot(data = dat,aes_string(x = "group",y=colnames(dat)[i]))+
geom_boxplot(aes(color = group))+
geom_jitter(aes(color = group))+
theme_bw()
}
library(patchwork)
wrap_plots(p,nrow = 2,guides = "collect")
# 分面也行的。
exp = matrix(rnorm(60),nrow = 10)
colnames(exp) <- paste0("sample",1:6)
rownames(exp) <- paste0("gene",1:10)
exp[1:4,1:4]
dat = data.frame(t(exp))
dat = mutate(dat,group = rep(c("A","B"),each = 3))
dat2 = gather(dat,key = "gene",value = "expression",-group)
ggplot(data = dat2)+
geom_boxplot(aes(x = group,y = expression,color = group))+
theme_bw()+
facet_wrap(~gene,nrow = 2)
3. 模拟出几个类似的文件,用R实现批量重命名
#生成文件
file.create(paste0(letters[1:3],'.txt'))
#重命名
getwd()
files <- list.files("/Users/hh/Desktop/practice") #填文件所在目录
oldName <- grep('\\.txt',files,value = TRUE)
newName=paste0(paste('HUI',1:3,sep = '_'),'.txt')
file.rename(oldName,newName)
网友评论