Jose R
Jose R

Reputation: 950

How do I interpolate a variable from one data frame to another matching time in R

I have data from two separate temperature data loggers. They both have Time and Celsius as columns. Below is code that will recreate a subset of 15 values from the two data loggers. They are typically off by a few seconds.

Time <- as.POSIXct(c("2014-07-16 13:09:38", "2014-07-16 13:09:48", "2014-07-16 13:09:58", "2014-07-16 13:10:08", "2014-07-16 13:10:18", "2014-07-16 13:10:28", "2014-07-16 13:10:38", "2014-07-16 13:10:48", "2014-07-16 13:10:58", "2014-07-16 13:11:08", "2014-07-16 13:11:18", "2014-07-16 13:11:28", "2014-07-16 13:11:38", "2014-07-16 13:11:48", "2014-07-16 13:11:58"))
Celsius <- c(27.5, 27.5, 27.5, 28, 28, 28, 28, 28, 28.5, 28.5, 28.5, 28.5, 28.5, 29, 29)
df1 <- data.frame(Time,Celsius)
Time <-  as.POSIXct(c("2014-07-16 13:09:39", "2014-07-16 13:09:49", "2014-07-16 13:09:59", "2014-07-16 13:10:09", "2014-07-16 13:10:19", "2014-07-16 13:10:29", "2014-07-16 13:10:39", "2014-07-16 13:10:49", "2014-07-16 13:10:59", "2014-07-16 13:11:09", "2014-07-16 13:11:19", "2014-07-16 13:11:29", "2014-07-16 13:11:39", "2014-07-16 13:11:49", "2014-07-16 13:11:59"))
Celsius <- c(26.6666666666667, 26.6666666666667, 26.6666666666667, 27.2222222222222, 27.2222222222222, 27.2222222222222, 27.2222222222222, 27.7777777777778, 27.7777777777778, 27.7777777777778, 27.7777777777778, 27.7777777777778, 28.3333333333333, 28.3333333333333, 28.3333333333333)
df2 <- data.frame(Time,Celsius)

How do I interpolate (linear) the Celsius on the second data frame matching to the times in the first data frame? I am ok with losing a few rows at the beginning or end.

Upvotes: 2

Views: 460

Answers (1)

MrFlick
MrFlick

Reputation: 206197

I think the approxfun will come in handy here. First of all, you want to make sure your temperature measurements are numeric. In your sample they seem to be factors for some reason, so you can change them with

df1$Celsius<-as.numeric(as.character(df1$Celsius))
df2$Celsius<-as.numeric(as.character(df2$Celsius))

Now we can use the approxfun on df2 to define a translation function from the date/time to the temp.

tx<-approxfun(df2$Time, df2$Celsius)

and then use that function on the df1$Time to get a prediction of the df2 temperature at each of the df1 times

tx(df1$Time)

Upvotes: 2

Related Questions