tidyverse 是一系列包的集合,其包含非常多的包和非常多的功能,非常值得学习!!

https://www.tidyverse.org/

比如可以好看的作图包ggplot,字符串处理的包 stringr,处理数据框的包dplyr等等。

用map 函数批量处理

map函数是一个函数家族,包含很多种具体的各种功能的map函数,也是tidyverse 集合的一个部分,它来自于包purrr。map 函数家族均将某个向量作为输入值,并输出“某种特定形式”的向量值。

用这种方法,我们可以处理向量中的每个元素、数据框中的每列、列表中的每个元素……

map 主要语法:

  1. map(object, function_to_apply)

map 函数家族包括以下这些:

  1. map() creates a list.
  2. map_lgl() creates a logical vector.
  3. map_int() creates an integer vector.
  4. map_dbl() creates a double or numeric vector.
  5. map_chr() creates a character vector.

用ggplot2可视化绘图

直接参考https://www.yuque.com/mugpeng/rr/wtz6tv系列吧~我太懒了~

强大のTidyverse

管道

虽然linux 的shell脚本语言语法很奇怪,而且有时让人百思不解其解!(或许这只是小白的愤怒!

但管道特性真的是太棒了~而tidyverse 也继承了这一优秀功能——提供了管道 %>%

可是,比起|,这也太复杂了吧!因此,R 也提供了快捷键辅助我们(command + shift + M),复习一下,赋值符号的快捷键是 alt + - , <-。

下面是使用管道的小例子:

  1. ## A single command
  2. sqrt(83)
  3. ## Base R method of running more than one command
  4. round(sqrt(83), digits = 2)
  5. ## Running more than one command with piping
  6. sqrt(83) %>% round(digits = 2)

tibbles

除了管道,tibble 是tidyverse 中的另外一个重要成分,它相当于“增强版” 的dataframe。

但tibble 也非常的固执己见(opininated),它认为列中的所有元素都应该被“公平对待”。

因此,它要求所有的行名都应该略去。

因此,当我们将dataframe 转为tibble 时,tidyverse 会将数据框的行名删去,需要注意!

  1. > f
  2. sample1 sample2 sample3 sample4 sample5
  3. gene1 4.498195 7.237380 2.569155 4.517381 9.641184
  4. gene2 3.871712 2.484628 6.089890 6.754401 8.031579
  5. gene3 9.152436 3.785714 2.153925 8.070671 7.389452
  6. gene4 3.468464 4.341664 3.015118 5.745573 6.062638
  7. > as_tibble(f)
  8. # A tibble: 4 x 5
  9. sample1 sample2 sample3 sample4 sample5
  10. <dbl> <dbl> <dbl> <dbl> <dbl>
  11. 1 4.50 7.24 2.57 4.52 9.64
  12. 2 3.87 2.48 6.09 6.75 8.03
  13. 3 9.15 3.79 2.15 8.07 7.39
  14. 4 3.47 4.34 3.02 5.75 6.06

我们可以用一个折中的方式,即先将行名转为一列,再将数据框转为tibble:

  1. > as_tibble(rownames_to_column(f))
  2. # A tibble: 4 x 6
  3. rowname sample1 sample2 sample3 sample4 sample5
  4. <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
  5. 1 gene1 4.50 7.24 2.57 4.52 9.64
  6. 2 gene2 3.87 2.48 6.09 6.75 8.03
  7. 3 gene3 9.15 3.79 2.15 8.07 7.39
  8. 4 gene4 3.47 4.34 3.02 5.75 6.06

tibble 其中一个好的特点就是,它不像dataframe那样霸占屏幕,当你并不知道数据框的大小且忘了限制其输出时,tibble 会非常友好的展示适合你电脑屏幕的信息:

  1. > f = tibble(iris)
  2. > f
  3. # A tibble: 150 x 5
  4. Sepal.Length Sepal.Width Petal.Length Petal.Width Species
  5. <dbl> <dbl> <dbl> <dbl> <fct>
  6. 1 5.1 3.5 1.4 0.2 setosa
  7. 2 4.9 3 1.4 0.2 setosa
  8. 3 4.7 3.2 1.3 0.2 setosa
  9. 4 4.6 3.1 1.5 0.2 setosa
  10. 5 5 3.6 1.4 0.2 setosa
  11. 6 5.4 3.9 1.7 0.4 setosa
  12. 7 4.6 3.4 1.4 0.3 setosa
  13. 8 5 3.4 1.5 0.2 setosa
  14. 9 4.4 2.9 1.4 0.2 setosa
  15. 10 4.9 3.1 1.5 0.1 setosa
  16. # … with 140 more rows

百宝箱

参考:https://www.yuque.com/mugpeng/rr/qng0vm