r - 如何按组加速转置data.frame?

标签 r dataframe

我有这个 data.frame具有相等长度的组 ( id )

id  |  amount 
--------------
 A  |   10   
 A  |   54   
 A  |   23   
 B  |   34   
 B  |   76    
 B  |   12    

我想转置 按组 id对此:
 id |
----------------------
 A  | 10  |  54 | 23  
 B  | 34  |  76 | 12

这样做的最有效方法是什么?

我以前用过 reshapedcast但他们确实很慢! (我有很多数据,很想加快这个瓶颈)

有没有更好的策略?使用 data.table还是矩阵??任何帮助将非常感激!
# Little data.frame
df <- data.frame(id=c(2,2,2,5,5,5), amount=as.integer(c(10,54,23,34,76,12)))

# Not so little data.frame
set.seed(10)
df <- data.frame(id = rep(sample(1:10000, 10000, replace=F),100), amount=as.integer(floor(runif(1000000, -100000,100000))))

# Create time variable
df$time <- ave(as.numeric(df$id), df$id, FUN = seq_along)

# The base R reshape strategy
system.time(df.reshape <-reshape(df, direction = "wide", idvar="id", timevar="time"))
user  system elapsed 
6.36    0.31    6.69 

# The reshape2 dcast strategy
require(reshape2)
a <- system.time(mm <- melt(df,id.vars=c('id','time'),measure.vars=c('amount')))
b <- system.time(df.dcast <- dcast(mm,id~variable+time,fun.aggregate=mean))
a+b
user  system elapsed 
14.44    0.00   14.45 

更新
利用每组长度相等的事实,您可以使用 matrix -功能。
df.matrix <- data.frame(id=unique(df$id), matrix(df$amount, nrow=(length(unique(df$id))), byrow=T))
user  system elapsed 
0.03    0.00    0.03 

注意:此方法假设 data.frame 由 id 预先排序.

最佳答案

矩阵方法将使用:

  system.time({ df.reshape <-matrix(df$amount, nrow=10000, byrow=TRUE); 
               rownames(df.reshape)<- df$id[1:10000]
             } )
   user  system elapsed 
  0.010   0.006   0.016 

关于r - 如何按组加速转置data.frame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14627096/

相关文章:

r - 有条件地将数据框中的值替换为第二个数据框中的值

r - Flexdashboard 中仪表颜色褪色

r - 列表的列(垂直)和列表

rlang:错误:无法将函数转换为字符串

根据列中的字符串从表中删除行

python - 如何从列表中删除每个项目的方括号

python - Pandas (如何修复): List is actually string and the value of length is misleading

python - 如何添加数据帧一列的字符串并形成另一列,该列将具有原始列的增量值

python - 删除数据框中的特定字符

python - 将数据帧聚合到嵌套字典 (python)