美文网首页生物信息学札记R基础知识R数据分析workshop
R数据科学 数据清洗透视-2 相关函数 pivot_longer

R数据科学 数据清洗透视-2 相关函数 pivot_longer

作者: 天地本无心 | 来源:发表于2020-08-31 18:50 被阅读0次

在上一篇文章中介绍了数据清晰透视相关的函数gather()和spread(),虽然函数名称看起来简单,但是简单也就意味着需要花更多的时间去分辨两个函数的差别,比如往哪个方向变化代表了传播(spread),哪个方向代表了聚集(gather)。所以在现在的R数据分析实践中,gather()和spread(), 已经逐渐不被推荐使用,因为我们有了更加合适的替代函数pivot_longer()和pivot_wider()。

1. pivot_longer()

还是用上次我们构造的mini_iris这个数据集举例。

attach(iris)
mini_iris <- iris[c(1,51,101),]
mini_iris
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1            5.1         3.5          1.4         0.2     setosa
51           7.0         3.2          4.7         1.4 versicolor
101          6.3         3.3          6.0         2.5  virginica

这个时候,我们需要将列名拆除,并且把原先的列名变成一个新的列变量的值,所有单元格的数字也变成一个新列。

pivot_longer()
pivot_longer(data = mini_iris,
             cols = c(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width),
             names_to = "flower_attr",
             values_to = "attr_value")
mini_iris %>% pivot_longer(cols = contains(c("Length", "width")),
             names_to = "flower_attr",
             values_to = "attr_value")
mini_iris %>% pivot_longer(contains(c("Length", "width")), "flower_attr","attr_value")

以上三种操作,本质上是相同的。都将我们的数据透视得更长了一些,让输出的数据框更“长”。

# A tibble: 12 x 3
   Species    flower_attr  value
   <fct>      <chr>        <dbl>
 1 setosa     Sepal.Length   5.1
 2 setosa     Petal.Length   1.4
 3 setosa     Sepal.Width    3.5
 4 setosa     Petal.Width    0.2
 5 versicolor Sepal.Length   7  
 6 versicolor Petal.Length   4.7
 7 versicolor Sepal.Width    3.2
 8 versicolor Petal.Width    1.4
 9 virginica  Sepal.Length   6.3
10 virginica  Petal.Length   6  
11 virginica  Sepal.Width    3.3
12 virginica  Petal.Width    2.5
2. pivot_wider()

同理,就像spread()之于gather(), pivot_wider()做和pivot_longer()相反的操作,即是将行里面的数据又还到列里面去, 让数据框看起来“变得更宽”。

tidy-8.png

只需要执行如下代码:

attach(iris)
mini_iris <- iris[c(1,51,101),]
flatted_data <- pivot_longer(data = mini_iris,
             cols = c(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width),
             names_to = "flower_attr",
             values_to = "attr_value")

flatted_data %>% pivot_wider(names_from = flower_attr, values_from = attr_value )

就能重新得到那个tidy dataframe了

# A tibble: 3 x 5
  Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
  <fct>             <dbl>       <dbl>        <dbl>       <dbl>
1 setosa              5.1         3.5          1.4         0.2
2 versicolor          7           3.2          4.7         1.4
3 virginica           6.3         3.3          6           2.5
参考资料
  • Hadley Wickham 所著 《R for data science》

相关文章

网友评论

    本文标题:R数据科学 数据清洗透视-2 相关函数 pivot_longer

    本文链接:https://www.haomeiwen.com/subject/zikpsktx.html