I have an array with repeating values, and I want to get the relative frequency (i.e., proportions) for each repeating value.
It seems natural to me to treat this as a 2-step procedure:
- count the occurrences of each value; and
- divide that count by the length of the original array.
To accomplish the first step we can use R.countBy()
from ramda.js
:
const R = require("ramda")
const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]
const counted = R.countBy(R.identity)(myLetters)
counted // => gives {"a": 4, "b": 2, "c": 4}
Now the second step would be to divide counted
by the length of myLetters
:
counted / R.length(myLetters) // obviously this doesn't work because it's not mapped
I'm a bit lost with how to map this correctly. My current clunky solution that I dislike:
// 1. manually calculate the length and store to a variable
const nvals = R.length(myLetters)
// 2. create a custom division function
const divide_by_length = (x) => R.divide(x, nvals)
// 3. map custom function to `counted`
R.map(divide_by_length, counted) // gives {"a": 0.4, "b": 0.2, "c": 0.4}
Although this works, there's gotta be a more straightforward way with ramda
to get from counted
to {"a": 0.4, "b": 0.2, "c": 0.4}
.