tidyverse 是一系列包的集合,其包含非常多的包和非常多的功能,非常值得学习!!
比如可以好看的作图包ggplot,字符串处理的包 stringr,处理数据框的包dplyr等等。
用map 函数批量处理
map函数是一个函数家族,包含很多种具体的各种功能的map函数,也是tidyverse 集合的一个部分,它来自于包purrr
。map 函数家族均将某个向量作为输入值,并输出“某种特定形式”的向量值。
用这种方法,我们可以处理向量中的每个元素、数据框中的每列、列表中的每个元素……
map 主要语法:
map(object, function_to_apply)
map 函数家族包括以下这些:
map() creates a list.
map_lgl() creates a logical vector.
map_int() creates an integer vector.
map_dbl() creates a “double” or numeric vector.
map_chr() creates a character vector.
用ggplot2可视化绘图
直接参考https://www.yuque.com/mugpeng/rr/wtz6tv系列吧~我太懒了~
强大のTidyverse
管道
虽然linux 的shell脚本语言语法很奇怪,而且有时让人百思不解其解!(或许这只是小白的愤怒!
但管道特性真的是太棒了~而tidyverse 也继承了这一优秀功能——提供了管道 %>%
。
可是,比起|
,这也太复杂了吧!因此,R 也提供了快捷键辅助我们(command + shift + M),复习一下,赋值符号的快捷键是 alt + -
, <-。
下面是使用管道的小例子:
## A single command
sqrt(83)
## Base R method of running more than one command
round(sqrt(83), digits = 2)
## Running more than one command with piping
sqrt(83) %>% round(digits = 2)
tibbles
除了管道,tibble
是tidyverse 中的另外一个重要成分,它相当于“增强版” 的dataframe。
但tibble 也非常的固执己见(opininated),它认为列中的所有元素都应该被“公平对待”。
因此,它要求所有的行名都应该略去。
因此,当我们将dataframe 转为tibble 时,tidyverse 会将数据框的行名删去,需要注意!
> f
sample1 sample2 sample3 sample4 sample5
gene1 4.498195 7.237380 2.569155 4.517381 9.641184
gene2 3.871712 2.484628 6.089890 6.754401 8.031579
gene3 9.152436 3.785714 2.153925 8.070671 7.389452
gene4 3.468464 4.341664 3.015118 5.745573 6.062638
> as_tibble(f)
# A tibble: 4 x 5
sample1 sample2 sample3 sample4 sample5
<dbl> <dbl> <dbl> <dbl> <dbl>
1 4.50 7.24 2.57 4.52 9.64
2 3.87 2.48 6.09 6.75 8.03
3 9.15 3.79 2.15 8.07 7.39
4 3.47 4.34 3.02 5.75 6.06
我们可以用一个折中的方式,即先将行名转为一列,再将数据框转为tibble:
> as_tibble(rownames_to_column(f))
# A tibble: 4 x 6
rowname sample1 sample2 sample3 sample4 sample5
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 gene1 4.50 7.24 2.57 4.52 9.64
2 gene2 3.87 2.48 6.09 6.75 8.03
3 gene3 9.15 3.79 2.15 8.07 7.39
4 gene4 3.47 4.34 3.02 5.75 6.06
tibble 其中一个好的特点就是,它不像dataframe那样霸占屏幕,当你并不知道数据框的大小且忘了限制其输出时,tibble 会非常友好的展示适合你电脑屏幕的信息:
> f = tibble(iris)
> f
# A tibble: 150 x 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
7 4.6 3.4 1.4 0.3 setosa
8 5 3.4 1.5 0.2 setosa
9 4.4 2.9 1.4 0.2 setosa
10 4.9 3.1 1.5 0.1 setosa
# … with 140 more rows