重新排列r中的数据帧
问题描述:
我正在尝试使用我拥有的一些现有库存数据。最终我想对数据生成加权回报,但我需要先改变它的结构。重新排列r中的数据帧
现有代码:
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
我所需要的数据(在这种情况下, “试”),在下面的格式:
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
谢谢
答
尝试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
+0
我相信Date〜Symbol是不够的,应该加上value.var =“Close”。 – user3838963
记住通过'dput()'共享数据' –