我有一个脚本应该随着时间的推移下载价格。它返回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 :(得分: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而不是merge(请参阅下面的代码)。这导致了不同的数据格式(每个价格点的观察都有一行),但它的作用是 - 在我看来 - 更接近你通常如何构造这种数据。
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")
}
}
答案 1 :(得分: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
}