0

リシェイプ機能に問題があります。しばらく疲れましたが、うまくいきません。私のデータは次のようになります。

    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
4

3 に答える 3

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))]
于 2012-11-06T08:55:11.010 に答える
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
于 2012-11-06T08:55:14.283 に答える
0

The "reshape" and "reshape2" packages generally get all the love, but there are options in base R too. Assuming your data.frame is called "df", here are two (and a half) options in base 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
于 2012-12-27T18:04:07.380 に答える