終極練習(xí)題
1.使用循環(huán)指郁,對(duì)iris的1到4列分別畫點(diǎn)圖(plot)
par(mfrow = c(2,2))
for (i in 1:4){
plot(iris[,i], col = iris[,5], ylab = colnames(iris)[i])
}
2.生成一個(gè)隨機(jī)數(shù)(rnorm)組成的10行6列的矩陣靶衍,
列名為sample1坯门,sample2….sample6,
行名為gene1遂庄,gene2…gene10,
分組為sample1劲赠、2涛目、3屬于A組,sample4凛澎、5霹肝、6屬于B組。
用循環(huán)對(duì)每個(gè)基因畫ggplot2箱線圖塑煎,并嘗試拼圖沫换。
- 循環(huán)
library(ggplot2)
exp <- matrix(rnorm(60), nrow = 10, ncol = 6,
dimnames = list(paste0("gene",1:10),
paste0("sample",1:6)))
#loop
dat <- as.data.frame(t(exp))
dat$group <- rep(c("A","B"),each = 3)
p <- list()
for (i in 1:10) {
p[[i]] <- ggplot(dat, aes_string("group", colnames(dat)[i], color = "group"))+
geom_boxplot()+
geom_jitter()
}
library(patchwork)
wrap_plots(p,nrow = 2,guides = "collect") #未知數(shù)量圖片(一列表)生成到一起
#aes() 寫什么映射什么,必須寫具體列名
#aes_string() 必須寫字符串最铁,若是代碼塊會(huì)先運(yùn)行讯赏,若結(jié)果是字符串即可
- 分面
#facet
library(tidyverse)
library(ggplot2)
exp <- matrix(rnorm(60), nrow = 10, ncol = 6,
dimnames = list(paste0("gene",1:10),
paste0("sample",1:6)))
exp %>%
t() %>%
as.data.frame() %>%
mutate(group = rep(c("A","B"),each = 3)) %>%
gather(geneid, nm, -group) %>%
ggplot(aes(group, nm, color = group))+
geom_boxplot()+
geom_jitter()+
facet_wrap(~geneid, nrow = 2)
3. 模擬出幾個(gè)類似的文件,用R實(shí)現(xiàn)批量重命名
f = c("a .txt","b .txt","c .txt")
for(i in 1:3){
file.create(f[[i]])
}
f2 = str_remove(f," ")
for(i in 1:3){
file.rename(f[[i]],f2[[i]])
}