1.使用循环,对iris的1到4列分别画点图(plot)
library(ggplot2)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箱线图,并尝试拼图。
gene_matrix1 = matrix(rnorm(10*6), nrow = 10); gene_matrix1gene_matrix1 <- data.frame(paste0("gene",1:10), gene_matrix1); gene_matrix1colnames(gene_matrix1) <- c("gene.id", paste0("samples",1:6)); gene_matrix1library(tidyr)gene_matrix1_long <- gather(data=gene_matrix1, key = "sample_nm", value = "gene_expression", -gene.id, factor_key = TRUE)head(gene_matrix1_long)gene_matrix1_long$group = ''; head(gene_matrix1_long)gene_matrix1_long$group[1:(3*10)] = "A"; head(gene_matrix1_long)gene_matrix1_long$group[(3*10+1):(6*10)] = "B"; tail(gene_matrix1_long)tmp <- gene_matrix1_long[gene_matrix1_long$gene.id == "gene1",]; tmpggplot(data=tmp, mapping = aes(x = group, y = gene_expression, color = group) ) + geom_boxplot()multi_plot <- list()for (i in 1:10){ tmp <- gene_matrix1_long[gene_matrix1_long$gene.id == paste0("gene",i),] multi_plot[[i]] <- ggplot(data=tmp, mapping = aes(x = group, y = gene_expression, color = group) ) + geom_boxplot()}library(gridExtra)do.call('grid.arrange',c(multi_plot, ncol = 5))
3. 模拟出几个类似的文件,用R实现批量重命名