James B
James B

Reputation: 51

Interpolating from data

Quick question here and I hope it has a quick answer.

This is my graph

Is there anyway to take an outside list of dates (dates that are not necessarily preexisting data points), and get their corresponding FUEL_PRICE values?

Appreciate any help.

EDIT: Here is an example of my data:

data1
       [date]    [fuel price] 
[1,]  01/15/2010     3.56           
[2,]  01/17/2010     3.32          
[3,]  03/18/2010     3.45           
[4,]  04/20/2010     3.94        
[4,]  04/25/2010     3.94      

and so on...

Is it possible to then ask what the fuel price would be for 02/15/2010 given the existing data?

Upvotes: 1

Views: 225

Answers (1)

G5W
G5W

Reputation: 37631

The function approxfun will create an interpolation function from data, but it expects numerical data as an input. I am assuming that your dates are available as strings, so we need to convert first from strings to dates using as.POSIXct then from a date to a number using as.numeric.

# Sample data
Data = read.table(text= "date    fuel_price 
01/15/2010     3.56           
01/17/2010     3.32          
03/18/2010     3.45           
04/20/2010     3.94        
04/25/2010     3.94", 
header=TRUE, stringsAsFactors=FALSE)

## Convert date strings to numbers
DateNum = as.numeric(as.POSIXct(Data$date, format="%m/%d/%Y"))

## fit a function to the data 
PriceFun = approxfun(Data$fuel_price ~ DateNum)

## Set up a function that will do the same pre-processing on new input. 
PriceFromDate = function(x) {
    round(PriceFun(as.numeric(as.POSIXct(x, format="%m/%d/%Y"))), 2) }

## Test with your example
PriceFromDate("02/15/2010 ")
[1] 3.38

## Everything is vectorized so you can give it a list of dates
PriceFromDate(c("02/15/2010 ", "02/20/2010"))
[1] 3.38 3.39

To read a csv, estimate the prices and write out the result , you will want something like

FuelData = read.csv("YourFile.csv", stringsAsFactors=FALSE)  
FuelData$EstPrice = PriceFromDate(FuelData$date)  
write.csv(FuelData, "NewFuelFile.csv")  

Upvotes: 1

Related Questions