看起来就像按行旋转一样pivot_longer()。stack()相比之下,gather按列拆分数据。\n我如何指定pivot_longer获得与 相同的结果gather()。\n我不需要额外的变量和排序,这正是关于pivot_longer参数的。
> all.equal(airquality %>% gather(), airquality %>% pivot_longer(everything(), names_to = "key", values_to = "value"))\n[1] "Attributes: < Component \xe2\x80\x9cclass\xe2\x80\x9d: Lengths (1, 3) differ (string compare on first 1) >"\n[2] "Attributes: < Component \xe2\x80\x9cclass\xe2\x80\x9d: 1 string mismatch >" \n[3] "Component \xe2\x80\x9ckey\xe2\x80\x9d: 764 string mismatches" \n[4] "Component \xe2\x80\x9cvalue\xe2\x80\x9d: 'is.NA' value mismatch: 44 in current 44 in target" \nRun Code Online (Sandbox Code Playgroud)\n
据我所知,没有控制排序的选项pivot_longer,但是您可以通过进行一些后处理来实现所需的顺序。
library(dplyr)\nlibrary(tidyr)\n\nairquality %>% \n pivot_longer(everything(), names_to = "key") %>%\n arrange(match(key, unique(key)))\n\n# key value\n# <chr> <dbl>\n# 1 Ozone 41\n# 2 Ozone 36\n# 3 Ozone 12\n# 4 Ozone 18\n# 5 Ozone NA\n# 6 Ozone 28\n# 7 Ozone 23\n# 8 Ozone 19\n# 9 Ozone 8\n#10 Ozone NA\n# \xe2\x80\xa6 with 908 more rows\nRun Code Online (Sandbox Code Playgroud)\n对于不同类别的列值的数据,我们需要先将它们转换为字符。例如ggplot2::diamonds:
ggplot2::diamonds %>% \n mutate(across(.fns = as.character)) %>% \n pivot_longer(everything(), names_to = "key") %>% \n arrange(match(key, unique(key))) \nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2225 次 |
| 最近记录: |