在r中重新排列数据帧

时间:2016-09-22 01:55:20

标签: r dataframe reshape2

我正在尝试使用我现有的一些库存数据。最终我想要对数据生成加权回报,但我需要先改变它的结构。

现有代码:

library(reshape2)
library(xts)
data <- read.csv(file="mini_r_weights.csv",head=TRUE,sep=",")
names(data)
wts=data[4]
head(wts)
head(data, n=18)
try=data[1:3]
try

输出:

> data <- read.csv(file="mini_r_weights.csv",head=TRUE,sep=",")

> names(data)
[1] "Date"   "Symbol" "Close"  "Weight"

> wts=data[4]

> head(wts)
  Weight
1    0.3
2    0.3
3    0.3
4    0.3
5    0.3
6    0.3

> head(data, n=18)
        Date Symbol     Close Weight
1  1/13/2012   AAPL  54.90965   0.30
2  1/17/2012   AAPL  55.54924   0.30
3  1/18/2012   AAPL  56.12606   0.30
4  1/19/2012   AAPL  55.94817   0.30
5  1/20/2012   AAPL  54.97374   0.30
6  1/23/2012   AAPL  55.90357   0.30
7  1/13/2012    DIS  36.19277   0.25
8  1/17/2012    DIS  36.26817   0.25
9  1/18/2012    DIS  36.77713   0.25
10 1/19/2012    DIS  37.17299   0.25
11 1/20/2012    DIS  37.05046   0.25
12 1/23/2012    DIS  36.99391   0.25
13 1/13/2012    IBM 158.84454   0.45
14 1/17/2012    IBM 159.58929   0.45
15 1/18/2012    IBM 160.53796   0.45
16 1/19/2012    IBM 160.05033   0.45
17 1/20/2012    IBM 167.14319   0.45
18 1/23/2012    IBM 168.43763   0.45

> try=data[1:3]

> try
        Date Symbol     Close
1  1/13/2012   AAPL  54.90965
2  1/17/2012   AAPL  55.54924
3  1/18/2012   AAPL  56.12606
4  1/19/2012   AAPL  55.94817
5  1/20/2012   AAPL  54.97374
6  1/23/2012   AAPL  55.90357
7  1/13/2012    DIS  36.19277
8  1/17/2012    DIS  36.26817
9  1/18/2012    DIS  36.77713
10 1/19/2012    DIS  37.17299
11 1/20/2012    DIS  37.05046
12 1/23/2012    DIS  36.99391
13 1/13/2012    IBM 158.84454
14 1/17/2012    IBM 159.58929
15 1/18/2012    IBM 160.53796
16 1/19/2012    IBM 160.05033
17 1/20/2012    IBM 167.14319
18 1/23/2012    IBM 168.43763

我需要以下格式的数据(在本例中为“try”):

Date            AAPL        DIS         IBM
1/13/2012   54.90964982 36.19276852 158.8445426
1/17/2012   55.54924437 36.26817012 159.5892927
1/18/2012   56.12605664 36.77713093 160.5379623
1/19/2012   55.94817349 37.17298933 160.0503284
1/20/2012   54.97374008 37.05046173 167.1431858
1/23/2012   55.90357191 36.99391053 168.4376323

谢谢

2 个答案:

答案 0 :(得分:1)

这可以使用reshape2 dcast函数完成。此问题之前已在此处得到解答,您可以阅读有关投射函数herehere

的更多信息

真的很快,这是你的看法:

d = dcast(try, Date~Symbol)

答案 1 :(得分:0)

尝试dcast,如下所示

library(reshape2)
library(xts)
data <-read.table(read.csv(file="mini_r_weights.csv",head=TRUE,sep=",")
names(data)
wts=data[4]
head(wts)
head(data, n=18)
try=data[1:3]
try
temp=dcast(data,Date~Symbol,value.var="Close")

结果

> temp
     Date     AAPL      DIS      IBM
1 1/13/12 54.90965 36.19277 158.8445
2 1/17/12 55.54924 36.26817 159.5893
3 1/18/12 56.12606 36.77713 160.5380
4 1/19/12 55.94817 37.17299 160.0503
5 1/20/12 54.97374 37.05046 167.1432
6 1/23/12 55.90357 36.99391 168.4376