Search code examples
f#deedle

lagging variables in F#


I have the following code:

let years = [|1990 .. 2010|]
let rand = System.Random()
let gold = [ for i in years do yield rand.NextDouble()]
let silver = [ for i in gold do yield 2.0 * i + rand.NextDouble()]
let x = Frame.ofColumns["gold"  => Series(years, gold);
                    "silver" => Series(years, silver) ]

I would like to regress gold on "lagged" silver. How can I edit the below code so that I regress gold on lagged silver (silver array shifted back by one)

let myresult = R.lm(formula = "gold~silver", data = (x |> R.as_data_frame)) 
R.summary(myresult)

Solution

  • You can use Series.shift 1 to shift the data in a series in a specified direction, so I think you can just construct the frame as follows:

    let x = 
      [ "gold"  => Series(years, gold);
        "silver" => (Series(years, silver) |> Series.shift 1) ]
      |> Frame.ofColumns
    

    Also, you do not need the R.as_data_frame call. This happens automatically :-)

    let myresult = R.lm(formula = "gold~silver", data = x) 
    R.summary(myresult)