重新调整面板数据从长到宽

时间:2014-03-21 12:23:17

标签: r reshape

我想将我的面板数据从长格式转换为宽格式。我知道有很多其他问题涉及这个问题,但是,我不相信他们中的任何一个都有我正在寻找的确切答案。

my.df <- data.frame(ID=rep(c("A","B","C"), 3), 
    TIME=rep(1:3, each=3), Price=1:9)
my.df

   ID TIME Price
1   A    1     1
2   B    1     2
3   C    1     3
4   A    2     4
5   B    2     5
6   C    2     6
7   A    3     7
8   B    3     8
9   C    3     9

  TIME Price-A Price-B Price-C
1    1       1       2       3
2    2       4       5       6
3    3       7       8       9

感谢您提供的任何帮助!弗朗西斯

2 个答案:

答案 0 :(得分:4)

您可以使用reshape

reshape(my.df,direction="wide", idvar = "TIME", timevar = "ID")


#    TIME Price.A Price.B Price.C
#     1       1       2       3
#     2       4       5       6
#     3       7       8       9

答案 1 :(得分:2)

或者您可以使用dcast包中的reshape2

require(reshape2)
dcast(my.df, TIME~ID, value.var="Price")

对于此特定示例,reshapedcast快。但如果data.frame变大,dcast会更快。

# your example data
require(microbenchmark)
microbenchmark(
  dcast(my.df, TIME~ID, value.var="Price")
  ,
  reshape(my.df,direction="wide", idvar = "TIME", timevar = "ID")
)
# Unit: milliseconds
#    expr      min       lq   median       uq      max  neval
#   dcast 2.655360 2.690616 2.718508 2.766484 4.396740    100
# reshape 2.156866 2.191007 2.221800 2.279147 3.896462    100

# my sample data
rows <- 10
LETTERS2 <- do.call(paste0, list(rep(LETTERS, 26), rep(LETTERS, each=26)))
LETTERS3 <- do.call(paste0, list(rep(LETTERS, 26), rep(LETTERS2, each=26)))
my.df <- data.frame(ID=rep(LETTERS3[1:rows], rows), 
                    TIME=rep(1:rows, each=rows), Price=1:(rows^2))
microbenchmark(
  dcast(my.df, TIME~ID, value.var="Price")
  ,
  reshape(my.df,direction="wide", idvar = "TIME", timevar = "ID")
)
# Unit: milliseconds
#   expr       min       lq   median       uq      max  neval
#  dcast  2.742831 2.795938 2.841681 2.912416 4.570789    100
# reshape 6.571011 6.667631 6.749746 6.857076 8.891662    100