gather() vs pivot_longer() 一切

gather() vs pivot_longer() on everything

看起来 pivot_longer() 的工作方式与 stack() 类似,因此按行旋转。相反 gather 按列拆分数据。 我如何指定 pivot_longer 以获得与 gather() 相同的结果。 我不想要额外的变量和排序,它正是关于 pivot_longer 参数。

> all.equal(airquality %>% gather(), airquality %>% pivot_longer(everything(), names_to = "key", values_to = "value"))
[1] "Attributes: < Component “class”: Lengths (1, 3) differ (string compare on first 1) >"
[2] "Attributes: < Component “class”: 1 string mismatch >"                                
[3] "Component “key”: 764 string mismatches"                                              
[4] "Component “value”: 'is.NA' value mismatch: 44 in current 44 in target"    

据我所知,在 pivot_longer 中没有控制排序的选项,但是您可以通过一些 post 处理来达到所需的顺序。

library(dplyr)
library(tidyr)

airquality %>% 
  pivot_longer(everything(), names_to = "key") %>%
  arrange(match(key, unique(key)))

#    key   value
#   <chr> <dbl>
# 1 Ozone    41
# 2 Ozone    36
# 3 Ozone    12
# 4 Ozone    18
# 5 Ozone    NA
# 6 Ozone    28
# 7 Ozone    23
# 8 Ozone    19
# 9 Ozone     8
#10 Ozone    NA
# … with 908 more rows

对于具有不同类列值的数据,我们需要先将它们转换为字符。例如 ggplot2::diamonds :

ggplot2::diamonds %>%      
  mutate(across(.fns = as.character)) %>%     
  pivot_longer(everything(), names_to = "key") %>%     
  arrange(match(key, unique(key)))