重塑 data.table:宽表转换

在 R 中使用 data.table 进行数据表连接

Scott Ritchie

Postdoctoral Researcher in Systems Genomics

将长表转换为宽表

sales_wide <- dcast(sales_long, quarter ~ year, value.var = "amount")

在 R 中使用 data.table 进行数据表连接

dcast() 函数

dcast() 的通用形式:

dcast(DT, ids ~ group, value.var = "values")
      |   |     |                   |
      |   |     |                    --> 拆分的列
      |   |      ----------------------> 用于拆分的分组标签
      |    ----------------------------> 作为标识符保留的行
       --------------------------------> 要重塑的 data.table            
在 R 中使用 data.table 进行数据表连接

dcast() 函数

sales_wide <- dcast(sales_long, quarter ~ year, value.var = "amount")

在 R 中使用 data.table 进行数据表连接

拆分多个值列

dcast(profit_long, quarter ~ year, value.var = c("revenue", "profit"))

在 R 中使用 data.table 进行数据表连接

多个行标识符

保留多列作为行标识符:

dcast(sales_long, quarter + season ~ year, value.var = "amount")

在 R 中使用 data.table 进行数据表连接

删除列

只有公式或 value.var 中包含的列会出现在结果中:

sales_wide <- dcast(sales_long, quarter ~ year, value.var = "amount")

在 R 中使用 data.table 进行数据表连接

多重分组

按多个分组列展开:

dcast(sales_long, quarter ~ department + year, value.var = "amount")

在 R 中使用 data.table 进行数据表连接

转换为矩阵

sales_wide <- dcast(sales_long, season ~ year, value.var = "amount")
sales_wide
   season    2015    2016
1: Autumn 3420000 3670000
2: Spring 2950000 3000300
3: Summer 2980700 3120200
4: Winter 3200100 3350000
在 R 中使用 data.table 进行数据表连接

转换为矩阵

as.matrix() 可将某列作为矩阵行名:

mat <- as.matrix(sales_wide, rownames = "season")
mat
       2015    2016        
Autumn 3420000 3670000
Spring 2950000 3000300
Summer 2980700 3120200
Winter 3200100 3350000
在 R 中使用 data.table 进行数据表连接

Passons à la pratique !

在 R 中使用 data.table 进行数据表连接

Preparing Video For Download...