2016-05-12 65 views
-1

對不起,問一個什麼可能似乎你們一個非常基本的問題上的東西,我想在R.列表列出來合併矩陣

我的數據做的是一個列表的列表。

dataset 
$Series1 
date  Value 
2015-11-01 1.301 
2015-11-02 6.016 
2015-11-03 4.871 
2015-11-04 10.925 
2015-11-05 7.638 

$Series2 
date  Value 
2015-11-01 1.532 
2015-11-02 3.730 
2015-11-03 6.910 
2015-11-04 3.554 
2015-11-05 2.631 

有關如何轉換爲以下內容的任何想法?

datamatrix 
date  Series1 Series2 
2015-11-01 1.301 1.532 
2015-11-02 6.016 3.730 
2015-11-03 4.871 6.910 
2015-11-04 10.925 3.554 
2015-11-05 7.638 2.631 
+0

您確定它是列表的列表嗎? – Divi

+0

是的,但它應該重要嗎? – MoreOnR

回答

1

您可以使用Reduce合併時間序列

dataset = list(Series1=read.table(text=" 
date  Value 
2015-11-01 1.301 
2015-11-02 6.016 
2015-11-03 4.871 
2015-11-04 10.925 
2015-11-05 7.638",header=TRUE,stringsAsFactors=FALSE),Series2=read.table(text=" 
date  Value 
2015-11-01 1.532 
2015-11-02 3.730 
2015-11-03 6.910 
2015-11-04 3.554 
2015-11-05 2.631",header=TRUE,stringsAsFactors=FALSE)) 

mergeFun = function(x,y) merge(x,y,by="date") 

datamatrix = Reduce(mergeFun,dataset) 
colnames(datamatrix) = c("date",names(dataset)) 

datamatrix 
#  date Series1 Series2 
# 2015-11-01 1.301 1.532 
# 2015-11-02 6.016 3.730 
# 2015-11-03 4.871 6.910 
# 2015-11-04 10.925 3.554 
# 2015-11-05 7.638 2.631 

使用xts庫多個系列

我已經在數據集中添加額外列,並使用xts你可以做到以下幾點

require(xts) 

dataset = list(Series1=read.table(text=" 
date  Value 
2015-11-01 1.301 
2015-11-02 6.016 
2015-11-03 4.871 
2015-11-04 10.925 
2015-11-05 7.638",header=TRUE,stringsAsFactors=FALSE),Series2=read.table(text=" 
date  Value 
2015-11-01 1.532 
2015-11-02 3.730 
2015-11-03 6.910 
2015-11-04 3.554 
2015-11-05 2.631",header=TRUE,stringsAsFactors=FALSE),Series3=read.table(text=" 
date  Value 
2015-11-01 1 
2015-11-02 3 
2015-11-03 6 
2015-11-04 3 
2015-11-05 2",header=TRUE,stringsAsFactors=FALSE),Series4=read.table(text=" 
date  Value 
2015-11-01 1.1 
2015-11-02 3.2 
2015-11-03 6.3 
2015-11-04 3.4 
2015-11-05 2.5",header=TRUE,stringsAsFactors=FALSE)) 


datasetXTS = lapply(dataset,function(x) { 
z=xts(x[,-1],order.by=as.Date(x[,1],format="%Y-%m-%d")); 
colnames(z) = tail(colnames(x),1); 
z 
}) 

datamatrix = Reduce(merge,datasetXTS) 

datamatrix 
#   Value Value.1 Value.2 Value.3 
#2015-11-01 1.301 1.532  1  1.1 
#2015-11-02 6.016 3.730  3  3.2 
#2015-11-03 4.871 6.910  6  6.3 
#2015-11-04 10.925 3.554  3  3.4 
#2015-11-05 7.638 2.631  2  2. 

該系列已正確合併,但由於您在所有系列中都有相同的列名,所以它們會重複。要解決此問題,請執行以下操作:

colnames(datamatrix) = names(dataset) 

datamatrix 
#   Series1 Series2 Series3 Series4 
#2015-11-01 1.301 1.532  1  1.1 
#2015-11-02 6.016 3.730  3  3.2 
#2015-11-03 4.871 6.910  6  6.3 
#2015-11-04 10.925 3.554  3  3.4 
#2015-11-05 7.638 2.631  2  2.5 
+0

感謝您的回覆。如果我在列表中有3個以上的系列,這種方法是行不通的? – MoreOnR

+0

它適用於列表中的任何數字系列,只要它們具有相同的公共列 – OdeToMyFiddle

+0

警告消息: 在merge.data.frame(x,y,by =「date」)中: 列名'Value.x','Value .y'在結果中是重複的 這是我得到的錯誤,如果有3個以上的系列。 – MoreOnR