通过R转换数据集



我的原始数据集

Transaction   Item   Amount   
       1001    200       14
       1001    201       13
       1001    202       16
       1001    205       17
       1002    300       11
       1002    305       12
       1002    200       30

我使用以下代码是基于一些专家的建议。

by(dx,dx$Transaction,function(x)c(x$Item,sum(x$Amount),x$Amount))

我当前的输出是。。。

dx$Transaction: 1001
[1] 200 201 202 205  60  14  13  16  17
------------------------------------------------------------------------------- 
dx$Transaction: 1002
[1] 300 305 200  53  11  12  30

但我想要的是

200 201 202 205  60  14  13  16  17
300 305 200  53  11  12  30

有可能去掉像…这样的标题吗。。。dx$Transaction: 1001?我有一百万行要通过这个函数处理。

如果需要,我可以使用其他功能。请帮忙。

如果所需的输出是"矩阵",我们可以使用stringi中的stri_list2matrix,它将把NAs填充到长度不等的列表元素中,并将"列表"转换为"矩阵"。

#your code
l1 <- by(dx,dx$Transaction,function(x)c(x$Item,sum(x$Amount),x$Amount))
library(stringi)
m1 <-  stri_list2matrix(l1, byrow=TRUE)
matrix(as.numeric(m1), ncol=ncol(m1))
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#[1,]  200  201  202  205   60   14   13   16   17
#[2,]  300  305  200   53   11   12   30   NA   NA

如果你喜欢把它放在一个列表中,只删除属性,一种方法是

lapply(seq_along(l1), function(i) l1[[i]])
#[[1]]
#[1] 200 201 202 205  60  14  13  16  17
#[[2]]
#[1] 300 305 200  53  11  12  30

或者将属性分配给NULL

attr(l1, 'dimnames') <- NULL
attr(l1, 'class') <- NULL
attr(l1, 'call') <- NULL
l1
#[[1]]
#[1] 200 201 202 205  60  14  13  16  17
#[[2]]
#[1] 300 305 200  53  11  12  30

数据

dx <- structure(list(Transaction = c(1001L, 1001L, 1001L, 1001L, 
1002L, 
1002L, 1002L), Item = c(200L, 201L, 202L, 205L, 300L, 305L, 200L
), Amount = c(14L, 13L, 16L, 17L, 11L, 12L, 30L)), 
.Names = c("Transaction", 
"Item", "Amount"), class = "data.frame", row.names = c(NA, -7L))

最新更新