2014-10-29 79 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 
}