2014-10-29 81 views
0

我有一個腳本,應該下載價格隨着時間的推移。它返回Date,Product,Price的數據幀。合併導致重複的列名

我想將它們結合起來,有這樣的循環:

for(product in products2){ 
    series=downloadPrices(product) 
    series$date= as.Date(series$date) 
    print(product) 
    if(new==FALSE){ 
    combined <-merge(combined,series,by="date") 
    print("merging") 
    }else{ 
    new=FALSE 
    combined=series 
    print("first one") 
    } 
} 

這導致:

column names 'underlying.x', 'price.x', 'underlying.y', 'price.y' are duplicated in the result 

我怎麼能力R創建underlying.z,price.z ...和等等?

刪除by =「date」結果爲空數據框。

如果在產品中只有3個元素,它可以正常工作。如果是四個,問題就會發生。

編輯:

數據集通過downladPrices下載:

date underlying price 
2012-01-03 00:00:00 Lollipop -1.66598985 
2012-01-04 00:00:00 Lollipop -2.77954315 
2012-01-05 00:00:00 Lollipop -3.82370558 
2012-01-06 00:00:00 Lollipop -4.90197970 
+0

示例數據集會更好。 'underlying.x'和'underlying.y'與'underlying'.x'和'underlying.z'相似。給我 – akrun 2014-10-29 12:10:24

+0

補充,請看看編輯 – LucasSeveryn 2014-10-29 12:15:36

回答

0

使用時只需將產品名稱作爲名稱的列:

for(product in products2){ 
    series=downloadPrices(product) 
    series$date= as.Date(series$date) 
    series = series[,c(1,3)] 
    names(series) = c("date",product) 
    print(product) 
    if(new==FALSE){ 
     combined <-merge(combined,series,by="date") 
     print("merging") 
    }else{ 
     new=FALSE 
     combined=series 
     print("first one") 
    } 
    } 

目標格式的詳細信息後更新爲補充說明,以下文字僅供參考

我會建議使用rbind而不是合併(請參閱下面的代碼)。這導致了不同的數據格式(每個價格點的觀察值都有一行),但它的工作原理和 - 在我的看法中 - 更接近於你通常如何構造這種數據。

for(product in products2){ 
    series=downloadPrices(product) 
    series$date= as.Date(series$date) 
    print(product) 
    if(new==FALSE){ 
     combined <-rbind(combined,series) 
     print("merging") 
    }else{ 
     new=FALSE 
     combined=series 
     print("first one") 
    } 
    } 
+0

這是一個很好的解決方案,但它不適合我的目的。我個人認爲,爲每個產品設立單獨的專欄更有意義。 – LucasSeveryn 2014-10-29 14:55:09

+0

現在我明白你的目標格式。然而,即使你的代碼不會讓你在那裏,因爲你每個產品有兩列,而不是一個(underlying_i和price_i)。我正在更新我的答案,以顯示如何輕鬆獲得目標格式。 – Valentin 2014-10-29 16:35:44

0

我通過添加重命名行來解決這個問題......它不是很漂亮,但它的工作。

我需要保持當前的格式:

date product product2 product3 
a b  c  d 
a b  c  d 
a b  c  d 

所以rbind不符合該法案。

對於任何有興趣的人,我使用plyr庫。

i=1 
for(product in products){ 
    series=downloadSpotByName(product, spotDateStart, dateEnd) 
    series=rename(series, c("underlying"=paste("underlying",i,sep=""),"price"=paste("price",i,sep=""))) 
    series$date= as.Date(series$date) 
    print(product) 
    if(new==FALSE){ 
    combined <-merge(combined,series,by="date") 
    print("merging") 
    }else{ 
    new=FALSE 
    combined=series 
    print("first one") 
    } 
    i=i+1 
}