简介:tidyr包的应用

tidyr主要提供了一个类似Excel中数据透视表(pivottable)的功能;gather和spread函数将数据在长格式和宽格式之间相互转化,应用在比如稀疏矩阵和稠密矩阵之间的转化;绘图和建模的数据整理separate和unite方法提供了数据分列拆分、合并的功能,应用在nominal数据==的转化上

R将整洁数据定义为:每个变量的数据存储在自身的列中,每个观测值的数据存储在其自身的行中。整洁数据是进行数据再加工的基础。

tidyr包主要涉及:

1)缺失值的简单补齐)长形表变宽形表与宽形表变长形表

  gather-把宽度较大的数据转换成一个更长的形式,它类比于从reshape包中融合函数的功能   spread-把长的数据转换成一个更宽的形式,它类比于从reshape包中铸造函数的功能。 gather()相反的是spread(),前者将不同的列堆叠起来,后者将同一列分开

3)列分割与列合并   separate-将一列按分隔符分割为多列   unite-将多列按指定分隔符合并为一列

tidyr包:(gather(宽数据转为长数据)、spread(长数据转为宽数据)、unite(多列合并为一列)、separate(将一列分离为多列))

codepractice

dataprep

##dataprea----

library(tidyverse)

head(mtcars)

tt.mtcars-as_tibble(mtcars)##不加参数,转化为tibble会丢失行名

tt.mtcars##行名变为数值

rownames(tt.mtcars)

tt.mtcars-as_tibble(mtcars,rownames=name)##加参数,将行名变为变量name

tt.mtcarsgatherandspread

##gatherlongertt-------------

#除name外,其余列聚合成两列,变量存在attr,对应的值存在value

tt.mtcars%%gather(key=attr,value=value,-name)

#只聚合disp到qsec的列

tt.mtcars%%gather(attr,value,disp:qsec)

##聚合指定的gear和carb列

tt.mtcars%%gather(attr,value,gear,carb)

tt.mtcars%%gather(attr,value,gear,carb)%%count(attr)

##聚合除name和cyl的所有列

tt.mtcars%%gather(attr,value,-name,-cyl)

tt.mtcars%%gather(attr,value,-name,-cyl)%%count(attr)

##spreadwidertt--------------

tt.gather-tt.mtcars%%gather(attr,value,-name)

tt.gather

##将长attr列,分散为多个变量列,value列的值分散为对应的值

tt.gather%%spread(attr,value)

uniteandseparate

##unitefewcolintolesscol----

##makeadf

set.seed(1)

year-01

month-sample(1:1,1)

day-sample(1:30,1)

hour-sample(1:1,1)

min-sample(0:60,1)

sec-sample(0:60,1)

event-sample(LETTERS,1)

tt-tibble(year,month,day,hour,min,sec,event)

tt

##组合year:sec变成date

tt%%unite(date,year:sec,sep=-)

tt1-tt%%unite(col=date,year:day,sep=-)

tt1

tt-tt1%%unite(col=time,hour:sec,sep=:)

tt

tt3-tt%%unite(date.time,date,time,sep=)

tt3

##separate1colintofewcol----

#分离datetime为date,和time两列

tt.sep1-tt3%%separate(col=date.time,into=c(date,time),sep=)

tt.sep1

tt.sep-tt.sep1%%separate(col=date,into=c(year,month,day),sep=-)

tt.sep

#separate(data=tt.sep1,col=date,into=c(year,month,day),sep=-)

##这里也感受到了,当会产生许多中间变量时,就可以考虑%%管道符号,不然没必要

##管道符号输入时,为啥不能tab选择参数了?

separate(data=tt.sep,col=time,into=c(hour,min,sec),sep=:)

##主要是这四个函数,还涉及replace_na()缺失值的简单补齐,之后再学~

参考

tidyr包:reshape的替代者,功能更纯粹:



转载请注明地址:http://www.tanhuaa.com/ncth/10973.html