Below is a simple for loop:
TSDF is of type "POSIXct" "POSIXt" and contains list of timestamps. LISTY is a list with timestamps and their respective values. Using below FOR loop, I need to go through the entire length of TSDF and whichever timestamp from TSDF is also available in DF, I need to assign it's value to newval. The below code works perfectly fine but it takes a long time if TSDF is too lengthy. Any suggestions how this code could be optimized ? Thanks in Advance. Appreciate.
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}
}
If I understand you correctly the following code will do what you want. Sadly your example data did not contain any values. Hence, I had to guess a bit. I also converted your list/vector into data frames for using merge.
#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"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.