2012-11-06 91 views
0

我有重塑功能的问题。我现在厌倦它,但它不起作用。我的数据是这样的:R重塑功能

KeyItem Year Value 
    Income  2011  10000 
    Income  2010  29299 
    Depth  2010  29393 
    Market Cap 2010  39393 
    Depth  2011  20000 
    Market Cap 2011  30000 

,我需要它看起来像这样我的功能:

KeyItem  2011   2010 
    Income   10000  29299 
    Depth   20000  29393 
    Market Cap  30000  39393 
+0

看到这个答案的各种方式来做到这一点的集合:http://stackoverflow.com/a/9617424/210673 – Aaron

回答

4

最简单的方法是使用dcast功能在reshape2包。首先,负载数据:

dd = read.table(textConnection("KeyItem Year Value 
Income 2011 10000 
Income 2010 29299 
Depth 2010 29393 
Market 2010 39393 
Depth 2011 20000 
Market 2011 30000"), header=TRUE) 

然后加载包:

library(reshape2) 

最后,只是dcast功能:

dcast(dd, KeyItem ~ Year) 

获得:

R> dcast(dd, KeyItem ~ Year) 
Using Value as value column: use value.var to override. 
    KeyItem 2010 2011 
1 Depth 29393 20000 
2 Income 29299 10000 
3 Market 39393 30000 

换一种方式,只需使用该melt功能:

melt(dcast(dd, KeyItem ~ Year)) 

您可以重新排序通常的方式列:

dd1 = dcast(dd, KeyItem ~ Year) 
dd1[,c("KeyItem", sort(colnames(dd1[, 2:ncol(dd1)]),TRUE))] 
+0

谢谢你,这正是我想要的。现在第一列是我的最后一年或最早的一年。有没有办法以另一种方式做到这一点。所以我的第一个专栏是我最近的一年? – MarMarko

+1

@MarMarko查看回答 – csgillespie

3
df <- read.table(text="KeyItem Year Value 
Income  2011  10000 
Income  2010  29299 
Depth  2010  29393 
Market_Cap 2010  39393 
Depth  2011  20000 
Market_Cap 2011  30000",header=TRUE) 

library(reshape2) 
df2 <- dcast(df,KeyItem~Year) 

#  KeyItem 2010 2011 
#1  Depth 29393 20000 
#2  Income 29299 10000 
#3 Market_Cap 39393 30000 
+0

谢谢你,这正是我想要的。现在第一列是我的最后一年或最早的一年。有没有办法以另一种方式做到这一点。所以我的第一年是我最近的一年? – MarMarko

+1

快速和肮脏:'df2 < - df2 [,c(1,3,2)]' – seancarmody

+0

它的工作,但有更好的方法吗? – MarMarko

0

的 “重塑” 和 “reshape2” 套餐普遍得到所有的爱,但在R中也有选项。假设你data.frame被称为“DF”,这里有两个(半)的基础R选项:

## Using base R reshape() 
reshape(df, direction = "wide", idvar="KeyItem", timevar="Year") 
#  KeyItem Value.2011 Value.2010 
# 1  Income  10000  29299 
# 3  Depth  20000  29393 
# 4 Market_Cap  30000  39393 

## Using xtabs() 
xtabs(Value ~ KeyItem + Year, df) 
#    Year 
# KeyItem  2010 2011 
# Depth  29393 20000 
# Income  29299 10000 
# Market_Cap 39393 30000 

## Here's the "half": Using xtabs(), but as a data.frame 
as.data.frame.matrix(xtabs(Value ~ KeyItem + Year, df)) 
#    2010 2011 
# Depth  29393 20000 
# Income  29299 10000 
# Market_Cap 39393 30000