2015-12-29 46 views
0

下面R代碼裏面的優化是循環簡單:與列表

TSDF的類型是「POSIXct」「POSIXt」,幷包含時間戳列表。 LISTY是一個包含時間戳和它們各自的值的列表。 使用下面的FOR循環,我需要通過TSDF的整個長度,並且從TSDF中的任何時間戳也可以在DF中使用,我需要將它的值賦給newval。下面的代碼工作得很好,但如果TSDF太長,則需要很長時間。任何建議如何可以優化此代碼?提前致謝。欣賞。

for(i in 1:length(TSDF)) 
{ 
    if(any(TSDF[[i]]==LISTY[[1]][,"DATETIMEST"])) 
    { 
    newval = LISTY[[1]][which(TSDF[[i]]==LISTY[[1]][,"DATETIMEST"]),"VALUE"] 
    } 
    else{newval = oldval} 

    if(any(TSDF[[i]]==LISTY[[2]][,"DATETIMEST"])) 
    { 
    newval = LISTY[[2]][which(TSDF[[i]]==LISTY[[2]][,"DATETIMEST"]),"VALUE"] 
    } 
    else{newval = oldval} 
} 
+0

請包含示例數據集'TSDF'和'LISTY'。 –

+0

這個問題可能更適合codereviews –

+0

TSDF < - as.POSIXct(c(「2015-12-19 23:40:04」,「2015-12-20 00:00:02」,「2015-12- 20 00:00:13「,」2015-12-20 00:00:17「,」2015-12-20 00:00:22「,」2015-12-20 00:00:27「)) –

回答

0

如果我正確理解你,下面的代碼將做你想做的。 可悲的是你的示例數據不包含任何值。因此,我不得不猜測一點。我還將您的列表/矢量轉換爲使用合併的數據框。

#generate some dummy data 
LISTY <- as.data.frame(list(x=as.POSIXct(c("2015-12-19 23:40:04", 
              "2015-12-20 00:00:02", 
              "2015-12-20 00:00:13")), 
          y=as.POSIXct(c("2015-12-20 00:00:17", 
              "2015-12-20 00:00:22", 
              "2015-12-20 00:00:27")), 
          val=c("a","b","c"))) 

tsdf.key <- as.POSIXct(c("2015-12-19 23:40:04", 
      "2015-12-20 00:00:02", 
      "2015-12-20 00:00:13", 
      "2015-12-20 00:00:17", 
      "2015-12-20 00:00:22", 
      "2015-12-20 00:00:27", 
      "2015-12-20 00:00:28")) 
tsdf.val <- 1:length(tsdf.key) 
TSDF <- data.frame(tsdf.key,tsdf.val) 
names(TSDF) <- c("key","value") 
names(LISTY)<-c("DATETIMEST","RECORDEDTIMESTAMP","value") 

# join data on left outer join 
merge1<- merge(x=TSDF,y=LISTY,by.x="key",by.y="DATETIMEST",all.x=TRUE) 
merge2<- merge(x=merge1,y=LISTY,by.x="key",by.y="RECORDEDTIMESTAMP",all.x=TRUE) 

###replace this by value 
#populate 
names(newval) <- c("newval") 
#fill in datetimestamp 
selector <- which(!is.na(merge2["value.y"])) 
newval <- merge2["value.x"] 
newval[selector] 
#fill in recordedtimespamp 
selector <- which(!is.na(merge2["value.y"])) 
newval <- merge2["value.x"]