I have a sequence of Country names in F#. I want to get how many of each distinct country entries do I have in the sequence.
The countBy examples in Microsoft docs and MSDN use if
and else
to get the Keys, but since I have ~240 distinct entries, I guess that I don't need to make an elif sentence for each entry, right?
So, is there an option to use another sequence to get the keys for the countBy?
#load "packages/FsLab/FsLab.fsx"
open FSharp.Data
open System
type City = JsonProvider<"city.list.json",SampleIsList=true>
let cities = City.GetSamples()
let Countries = seq { for city in cities do yield city.Country.ToString() } |> Seq.sort
let DistinctCountries = Countries |> Seq.distinct
//Something like this
let Count = Seq.countBy DistinctCountries Countries
Anyone interested in my city.list.json
Update
My input sequence is something like this (with a lot more of entries) with each code repeated as many cities for that country are in the original list:
{ "AR","AR","AR","MX","MX" }
As a result I expect:
{("AR", 3),("MX", 2),...}
Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Call the sort function and pass the array and the size of an array as a parameter. Take a temporary variable that will store the count of distinct elements. Print the result.
To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.
Countries |> Seq.countBy id
id
is the identity function fun x -> x
. Use this because the "key" here is the sequence item itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With