Skip to content

Instantly share code, notes, and snippets.

@tixxit
Last active August 29, 2015 14:10
Show Gist options
  • Save tixxit/5a32fd834fd77d62d69d to your computer and use it in GitHub Desktop.
Save tixxit/5a32fd834fd77d62d69d to your computer and use it in GitHub Desktop.
resolvers += "Pellucid Bintray" at "http://dl.bintray.com/pellucid/maven"
libraryDependencies += "com.pellucid" %% "framian" % "0.3.3"
package example
import scala.collection.mutable.ArrayBuffer
import framian._
import framian.csv._
import spire.implicits._
object Main extends App {
// Populate the array buffers with some values. I made values an
// `ArrayBuffer[Double]` instead of `ArrayBuffer[String]` to show that you
// can mix types in a Frame.
val values = ArrayBuffer[Double](1.2, 3.4, 5.6)
val times = ArrayBuffer[String]("1", "3", "2")
val ids = ArrayBuffer[String]("Alice", "Bob", "Charlie")
// Loading values into a Frame as the columns. We use `mergeColumns` here.
// This method takes a tuple of column / series pairs. In this case, we are
// providing a 3-tuple with each of our columns converted to a Series[Int,
// Double] or Series[Int, String]. The keys in this case are just the index
// into the array buffer of the value.
val frame: Frame[Int, String] = Frame.mergeColumns(
"id" -> Series(ids: _*),
"time" -> Series(times: _*),
"value" -> Series(values: _*)
)
// Extracting the *values* as a Double. Cols by default will return values as
// a Rec, which is rarely what we want. Instead, we use the `.as[T]` method to
// have the values returned as type `Double` (via `.as[Double]`).
//
// Also, we use foreachDense here so that we only get non-missing values (as
// type `Double`), instead of cells (as type `Cell[Double]`).
println("Values:")
frame.get(Cols("value").as[Double]).foreachDense { (row, value) =>
println(s"$row:$value")
}
println()
// We can reindex the Frame by the IDs if we prefer. Here we'll just print
// the values again as above, but with the ID instead of the row number.
val frame2: Frame[String, String] = frame.reindex(Cols("id").as[String])
println("Values:")
frame2.get(Cols("value").as[Double]).foreachDense { (id, value) =>
println(s"$id:$value")
}
println()
// Converting to a CSV. We add a header to the CSV, since the default CSV
// format does not.
val fmt = CsvFormat.CSV.withHeader(true)
val csv = Csv.fromFrame(fmt)(frame)
println("Csv:")
println(csv.toString)
}
Values:
0:1.2
1:3.4
2:5.6
Values:
Alice:1.2
Bob:3.4
Charlie:5.6
Csv:
id,time,value
Alice,1,1.2
Bob,3,3.4
Charlie,2,5.6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment