R类型提供者和Ggplot2

时间:2013-05-29 17:21:35

标签: r f# type-providers

有人用过吗? 我不介意看一个简短的例子来快速启动。

我可以运行example.fsx脚本:acf函数副作用显示在图表上。

但我不知道如何出现ggplot图形。

open RProvider.ggplot2
open RProvider.utils

R.setwd @"C:/code/pp/Datasets/output/Kaggle/dontgetkicked"
let f = R.read_csv("measure_DNGtraining.csv")
R.qplot("erase_rate", "components",f)

产生一个

val it : SymbolicExpression =
  RDotNet.SymbolicExpression {Engine = RDotNet.REngine;
                              IsClosed = false;
                              IsInvalid = false;
                              IsProtected = true;
                              Type = List;}

我正在阅读说明,但是如果有人有一个方便小部件......

2 个答案:

答案 0 :(得分:12)

我认为你需要将结果表达式传递给R.print

R.qplot("erase_rate", "components",f)
|> R.print 

通过F#类型提供程序使用ggplot2的问题是ggplot2库有点太聪明了。我正在玩这个有一段时间,只要你只使用qplot函数,它看起来效果很好。如果你想做一些更有趣的事情,那么将R代码写成字符串并调用R.eval可能更容易。要做到这一点,你需要:

// Helper function to make calling 'eval' easier
let eval (text:string) =
  R.eval(R.parse(namedParams ["text", text ]))

eval("library(\"ggplot2\")")

// Assuming we have dataframe 'ohlc' with 'Date' and 'Open'
eval("""
  print(
    ggplot(ohlc, aes(x=Date, y=Open)) + 
    geom_line() + 
    geom_smooth()
  )
  """)

我还花了一些时间来弄清楚如何将数据从F#传递到R(即根据来自F#的数据创建R数据帧,就像CSV类型提供者一样)。因此,为了填充ohlc数据框,我使用了这个(其中SampleData是Yahoo的CSV提供商):

let df =
  [ "Date",  box [| for r in SampleData.msftData -> r.Date |]
    "Open",  box [| for r in SampleData.msftData -> r.Open |]
    "High",  box [| for r in SampleData.msftData -> r.High |]
    "Low",   box [| for r in SampleData.msftData -> r.Low |]
    "Close", box [| for r in SampleData.msftData -> r.Close |] ]
  |> namedParams
  |> R.data_frame
R.assign("ohlc", df)

答案 1 :(得分:3)

正如Tomas指出的那样,你需要打印ggplot2的结果来显示任何内容。

我们通过在标准F#交互式启动脚本中向fsi会话添加打印机来实现此目的:

fsi.AddPrinter(fun (sexp: RDotNet.SymbolicExpression) -> sexp.Print())

这使得RProvider更有用,因为它以与在R中打印相同的方式打印每个操作的结果。