From 94ece3546e9732ebd87be9a74644aadcd9c8cacb Mon Sep 17 00:00:00 2001 From: kortschak Date: Mon, 5 Jun 2017 13:58:36 +0930 Subject: [PATCH] floats: add ParseWithNA --- floats/floats.go | 14 ++++++++++++ floats/parse_example_test.go | 43 ++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 floats/parse_example_test.go diff --git a/floats/floats.go b/floats/floats.go index 7f1cadce..32b645ba 100644 --- a/floats/floats.go +++ b/floats/floats.go @@ -14,6 +14,7 @@ import ( "errors" "math" "sort" + "strconv" "gonum.org/v1/gonum/internal/asm/f64" ) @@ -567,6 +568,19 @@ func Norm(s []float64, L float64) float64 { return math.Pow(norm, 1/L) } +// ParseWithNA converts the string s to a float64 in v. +// If s equals missing, w is returned as 0, otherwise 1. +func ParseWithNA(s, missing string) (v, w float64, err error) { + if s == missing { + return 0, 0, nil + } + v, err = strconv.ParseFloat(s, 64) + if err == nil { + w = 1 + } + return v, w, err +} + // Prod returns the product of the elements of the slice. // Returns 1 if len(s) = 0. func Prod(s []float64) float64 { diff --git a/floats/parse_example_test.go b/floats/parse_example_test.go new file mode 100644 index 00000000..cb8c4e51 --- /dev/null +++ b/floats/parse_example_test.go @@ -0,0 +1,43 @@ +// Copyright ©2017 The gonum Authors. All rights reserved. +// Use of this code is governed by a BSD-style +// license that can be found in the LICENSE file + +package floats_test + +import ( + "bufio" + "fmt" + "log" + "strings" + + "gonum.org/v1/gonum/floats" + "gonum.org/v1/gonum/stat" +) + +func ExampleParseWithNA() { + // Calculate the mean of a list of numbers + // ignoring missing values. + const data = `6 +missing +4 +` + + var vals, weights []float64 + sc := bufio.NewScanner(strings.NewReader(data)) + for sc.Scan() { + v, w, err := floats.ParseWithNA(sc.Text(), "missing") + if err != nil { + log.Fatal(err) + } + vals = append(vals, v) + weights = append(weights, w) + } + err := sc.Err() + if err != nil { + log.Fatal(err) + } + fmt.Println(stat.Mean(vals, weights)) + + // Output: + // 5 +}