1.使用循环,对iris的1到4列分别画点图(plot)

  1. library(ggplot2)
  2. par(mfrow = c(2,2))
  3. for (i in 1:4){
  4. plot(iris[,i], col = iris[,5])
  5. }

小洁老师布置作业之终极练习题 - 图2

2.生成一个随机数(rnorm)组成的10行6列的矩阵,列名为sample1,sample2….sample6,行名为gene1,gene2…gene10,分组为sample1、2、3属于A组,sample4、5、6属于B组。用循环对每个基因画ggplot2箱线图,并尝试拼图。

  1. gene_matrix1 = matrix(rnorm(10*6), nrow = 10); gene_matrix1
  2. gene_matrix1 <- data.frame(paste0("gene",1:10), gene_matrix1); gene_matrix1
  3. colnames(gene_matrix1) <- c("gene.id", paste0("samples",1:6)); gene_matrix1
  4. library(tidyr)
  5. gene_matrix1_long <- gather(data=gene_matrix1,
  6. key = "sample_nm",
  7. value = "gene_expression",
  8. -gene.id,
  9. factor_key = TRUE)
  10. head(gene_matrix1_long)
  11. gene_matrix1_long$group = ''; head(gene_matrix1_long)
  12. gene_matrix1_long$group[1:(3*10)] = "A"; head(gene_matrix1_long)
  13. gene_matrix1_long$group[(3*10+1):(6*10)] = "B"; tail(gene_matrix1_long)
  14. tmp <- gene_matrix1_long[gene_matrix1_long$gene.id == "gene1",]; tmp
  15. ggplot(data=tmp, mapping = aes(x = group, y = gene_expression, color = group) ) +
  16. geom_boxplot()
  17. multi_plot <- list()
  18. for (i in 1:10){
  19. tmp <- gene_matrix1_long[gene_matrix1_long$gene.id == paste0("gene",i),]
  20. multi_plot[[i]] <- ggplot(data=tmp, mapping = aes(x = group, y = gene_expression, color = group) ) +
  21. geom_boxplot()
  22. }
  23. library(gridExtra)
  24. do.call('grid.arrange',c(multi_plot, ncol = 5))

小洁老师布置作业之终极练习题 - 图33. 模拟出几个类似的文件,用R实现批量重命名