Tidyverse补充

时间:2022-07-25
本文章向大家介绍Tidyverse补充,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Tidyverse补充

sunqi

2020/8/13

概述

休息了几天,罪过

tidyverse中的长款数据转换函数,类比于之前的reshape2包中的melt和dcast函数

代码

rm(list=ls())
library(tidyverse)
library(patchwork)
# 建立示例数据框
df <- data.frame(
  Day = 1:5,
  type1 = c(0.6, 1.2, 1.4, 1.9, 2.2),
  type2 = c(0.5, 0.7, 0.9, 1.3, 1.8)
)
# 在绘图的过程中
# 尤其是ggplot函数,上述的宽数据格式无法满足绘图的需要
# 涉及分组绘图
# 对于type1和type2
# 因此需要长款转换
# 需要的函数
# pivot_longer 转换长
# pivot_wider 转换宽
long <- pivot_longer(df, 2:3,
  names_to = "type",#用于显示变量的名字
  values_to = "value"#用于显示值的名字
)
long %>% head()
## # A tibble: 6 x 3
##     Day type  value
##   <int> <chr> <dbl>
## 1     1 type1   0.6
## 2     1 type2   0.5
## 3     2 type1   1.2
## 4     2 type2   0.7
## 5     3 type1   1.4
## 6     3 type2   0.9
long<-df %>%
  pivot_longer(
  cols = -Day, # 这里去掉day,其实和2:3是一个意思
  names_to = "type",
  values_to = "value"
  ) %>% head()
# 此时间就可以直接绘图
long %>%
  ggplot(aes(x = Day, y = value, color = type)) +
  geom_line()
# 长数据转换宽数据
# 此时又回到了之前的数据
long %>%
  pivot_wider(
  names_from = "type",
  values_from = "value"
) %>% head()
## # A tibble: 3 x 3
##     Day type1 type2
##   <int> <dbl> <dbl>
## 1     1   0.6   0.5
## 2     2   1.2   0.7
## 3     3   1.4   0.9
# count函数
## 计数函数,类比table函数
iris %>% count(Species)
##      Species  n
## 1     setosa 50
## 2 versicolor 50
## 3  virginica 50
# 添加一列显示每个花卉的数目

iris %>%
  group_by(Species) %>%
  mutate(n = n()) %>%
  ungroup() %>%
  select(Species,n) %>%
  head()
## # A tibble: 6 x 2
##   Species     n
##   <fct>   <int>
## 1 setosa     50
## 2 setosa     50
## 3 setosa     50
## 4 setosa     50
## 5 setosa     50
## 6 setosa     50
# 同时还有更简单的方法

iris %>% add_count(Species) %>% head()
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species  n
## 1          5.1         3.5          1.4         0.2  setosa 50
## 2          4.9         3.0          1.4         0.2  setosa 50
## 3          4.7         3.2          1.3         0.2  setosa 50
## 4          4.6         3.1          1.5         0.2  setosa 50
## 5          5.0         3.6          1.4         0.2  setosa 50
## 6          5.4         3.9          1.7         0.4  setosa 50

结束语

不知道写点啥,就这样吧。

PEACE