我有一大堆data.frames與不規則的時間間隔。R合併data.frames asof加入
我想創建一個新的data.frame並將其他人加入到它中,以便每個data.frame都從新的data.frame中挑選最新值。
例如,下面的listOfDataFrames包含data.frames列表,每個data.frames都有一個秒列的時間列。我找到了總範圍,將範圍調整爲60,然後將其調整以獲得整整一分鐘的增加的seqn。現在我需要將data.frames列表合併到這個新seqn的左側。例如如果mypoints值是60,該值連接到它應該是最新值< = 60
xrange <- range(lapply(listOfDataFrames,function(x) range(x$Time)))
mypoints <- 60*do.call(seq,as.list(xrange%/%60))
我相信這有時被稱爲ASOF加入。
有沒有一個簡單的程序來做到這一點?
感謝
編輯:這就是我目前使用
xrange <- range(lapply(listOfDataFrames,function(x) range(x$Time)))
mypoints <- 60*seq(xrange[1]%/%60,1+xrange[2]%/%60)
result <- data.frame(Time=mypoints)
for(index in 1:length(listOfDataFrames))
{
x<-listOfDataFrames[[index]]
indices <- which(sort(c(mypoints,x$Time)) %in% mypoints) - 1:length(mypoints)
indices[indices==0] <- NA
newdf<-data.frame(new=x$Result[indices])
colnames(newdf)<-paste("S",index,sep="")
result <- cbind(result,newdf)
}
編輯:完整的例子
AsOfJoin <- function (listOfDataFrames) {
xrange <- range(lapply(listOfDataFrames,function(x) range(x$Time)))
mypoints <- 60*seq(xrange[1]%/%60,1+xrange[2]%/%60)
result <- data.frame(Time=mypoints)
for(index in 1:length(listOfDataFrames))
{
x<-listOfDataFrames[[index]]
indices <- which(sort(c(mypoints,x$Time)) %in% mypoints) - 1:length(mypoints)
indices[indices==0] <- NA
newdf<-data.frame(new=x$Result[indices])
colnames(newdf)<-paste("S",index,sep="")
result <- cbind(result,newdf)
}
result[is.na(result)]<-0
result
}
a<-data.frame(Time=c(28947.5,28949.6,29000),Result=c(10,15,9))
b<-data.frame(Time=c(28947.8,28949.5),Result=c(14,19))
listOfDataFrames <- list(a,b)
result<-AsOfJoin(listOfDataFrames)
> a
Time Result
1 28947.5 10
2 28949.6 15
3 29000.0 9
> b
Time Result
1 28947.8 14
2 28949.5 19
> result
Time S1 S2
1 28920 0 0
2 28980 15 19
3 29040 9 19
您能提供一個小例子,或許是一個2-3個數據框的列表來說明您的問題嗎?另外,如果沒有*唯一的*最新值<= 60,你打算怎麼辦? – joran
列表應該全部排序。想象一下等候室裏的病人數量,他們隨機到達每一秒鐘。我們想知道有多少人每分鐘都在等待,然後加入,例如5個工作日。 – Cookie
通過讓他們「想象」一些數據,你不會增加某人幫助他人的機率。幫助我們幫助你。 –