作者:黄天元,复旦大学博士在读,热爱数据科学与开源工具(R),致力于利用数据科学迅速积累行业经验优势和科学知识发现,涉猎内容包括但不限于信息计量、机器学习、数据可视化、应用统计建模、知识图谱等,著有《R语言数据高效处理指南》。知乎专栏:R语言数据挖掘。邮箱:huang.tian-yuan@qq.com.欢迎合作交流。
当前,tidyfst已经到了它的0.9.3版本,很多函数都基本定型了,后面会到比较稳定的开发状态。由于数据长宽转换这个步骤,看起来简单,其实充满智慧,因此在这次版本更新中又做了新的调整。但是总体理念是不变的,让大家记得住,做得好,跑得快。
还是以R for Data Science的例子作为示范(12 Tidy data | R for Data Science),来看tidyfst中的长宽转换究竟如何实现。
我们有什么?
library(pacman)
p_load(tidyr,tidyfst)
table4a
#> # A tibble: 3 x 3
#> country `1999` `2000`
#> * <chr> <int> <int>
#> 1 Afghanistan 745 2666
#> 2 Brazil 37737 80488
#> 3 China 212258 213766我们想干啥?

那么这个原始表格中,country称之为不变列,year称为命名列(name),cases称为数值列(value)。那么,我们可以这样实现:
table4a %>%
longer_dt(country,name = "year",value = "cases")
#> country year cases
#> <char> <fctr> <int>
#> 1: Afghanistan 1999 745
#> 2: Brazil 1999 37737
#> 3: China 1999 212258
#> 4: Afghanistan 2000 2666
#> 5: Brazil 2000 80488
#> 6: China 2000 213766肯定有人希望选择数据列,其实是完全没问题的。你可以通过排除数据列来选择不变列,下面是实现方法:
table4a %>%
longer_dt(-"1999|2000",name = "year",value = "cases")如果变量比较多,可以按照位置来选:
table4a %>%
longer_dt(-(2:3),name = "year",value = "cases")所有select_mix能够使用的选择方法(关于tidyfst选择的灵活,可以参照HopeR:为什么你要使用tidyfst的select_dt),它统统可以,但是我们规约:只选不变列。
我们有什么?
table2
#> # A tibble: 12 x 4
#> country year type count
#> <chr> <int> <chr> <int>
#> 1 Afghanistan 1999 cases 745
#> 2 Afghanistan 1999 population 19987071
#> 3 Afghanistan 2000 cases 2666
#> 4 Afghanistan 2000 population 20595360
#> 5 Brazil 1999 cases 37737
#> 6 Brazil 1999 population 172006362
#> # … with 6 more rows我们想干啥?(图中key和value应该为type和count)

如何实现?
table2 %>%
wider_dt(country,year,name = "type",value = "count")
#> country year cases population
#> <char> <int> <int> <int>
#> 1: Afghanistan 1999 745 19987071
#> 2: Afghanistan 2000 2666 20595360
#> 3: Brazil 1999 37737 172006362
#> 4: Brazil 2000 80488 174504898
#> 5: China 1999 212258 1272915272
#> 6: China 2000 213766 1280428583我们依旧是把不变列放在最前面,然后name和value中放的列,与上文一致。自然也支持正则:
table2 %>%
wider_dt("country|year",name = "type",value = "count")如果除了name和value以外,全部都是不变列,你可以干脆不选:
table2 %>%
wider_dt(name = "type",value = "count")就是这么任性。
至此,tidyfst长宽转换简介结束。其实它还有很多黑科技,但是我还是按下不表,让大家自由探索~
原文作者:;如有侵权,请联系管理员删除。