Hi- I have two data frames for which I wish to conditionally subtract the values of one dataframe from the other.
I want to subtract df1$x from df2$x when their id is equal and the absolute value of difference between the dates is 12 hours or less. If there is no match of equal id's and dates less than 12 hours apart I want it to return "NA". Note that df1 has missing values in x and y columns, but df2 does not have any missing values. I think I'm close with the code at the end, but would appreciate a bit of help getting over this hurdle. Sample dataframes follow: *df1<-* ID Date y x STM07.1 30-05-2007 18:48 STM07.1 30-05-2007 20:21 STM07.1 02-06-2007 09:39 -20.101 -134.421 STM07.1 02-06-2007 17:36 STM07.1 03-06-2007 20:31 STM07.1 05-06-2007 08:34 STM07.2 19-02-2007 00:00 -37.4082 178.34395 STM07.2 10-03-2007 19:58 STM07.2 23-03-2007 06:33 STM07.2 23-03-2007 17:02 STM07.2 24-03-2007 04:27 -31.164 178.765 STM07.2 24-03-2007 11:35 STM07.2 25-03-2007 06:41 -31.181 178.77 STM07.2 26-03-2007 05:11 ** *df2<-* ID Date y x STM07.1 31/05/2007 23:00 -20.8291 217.7022 STM07.1 1/06/2007 11:00 -20.825 217.698 STM07.1 1/06/2007 23:00 -20.8224 217.70115 STM07.2 19/02/2007 0:00 -37.4096 178.306 STM07.2 19/02/2007 12:00 -37.3752 178.336 STM07.2 20/02/2007 0:00 -37.277 178.378 STM07.2 20/02/2007 12:00 -37.1786 178.3845 STM07.2 21/02/2007 0:00 -37.076 178.389 STM07.2 21/02/2007 12:00 -36.9197 178.3965 STM07.2 22/02/2007 0:00 -36.7435 178.391 STM07.2 22/02/2007 12:00 -36.4925 178.509 STM07.2 23/02/2007 0:00 -36.2415 178.575 STM07.2 23/02/2007 12:00 -35.955 178.628 d.x <- ifelse(c(test = df1$ID==df2$ID && abs(difftime(as.POSIXlt(df1$Date), as.POSIXlt(df2$Date), units="hours") < 12)), yes = delta.lon=df1$x-df2$x, no = "NA") I'm using R 2.7.1. Cheers, Tim [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.