How to Count Frequency in Julia
Description
In Julia, to count the frequencies of elements inside an object you can use the functions countmap or counts. Both require loading the package StatsBase before use.
countmap—as its name suggests—returns pairs of elements and their counts. Only values contained in the input appear in the result.
julia> countmap(x)
Dict{Int64, Int64} with 4 entries:
값1 => 값1의 빈도
값2 => 값2의 빈도
값3 => 값3의 빈도
값4 => 값4의 빈도
In contrast, counts produces a vector as output and can only be used with integers. See the code below for details.
countmap
It works with a vector of integers, a vector of characters, a matrix, or a string.
julia> x = rand(0:4, 100)
100-element Vector{Int64}:
0
4
⋮
4
1
julia> countmap(x)
Dict{Int64, Int64} with 5 entries:
0 => 28
4 => 20
2 => 13
3 => 16
1 => 23
julia> s = rand('a':'e', 100)
100-element Vector{Char}:
'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
⋮
'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase)
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
julia> A = rand(0:4, (10,10))
10×10 Matrix{Int64}:
2 4 3 1 2 3 3 3 3 0
1 0 3 2 0 0 3 0 3 1
⋮ ⋮
2 0 1 3 4 4 2 0 4 4
1 4 4 4 2 1 2 1 0 4
julia> countmap(A)
Dict{Int64, Int64} with 5 entries:
0 => 19
4 => 24
2 => 15
3 => 22
1 => 20
julia> foo = "asdflk23f90cxnvjkcdsafalj;fdwaelkf"
"asdflk23f90cxnvjkcdsafalj;fdwaelkf"
julia> countmap(foo)
Dict{Char, Int64} with 18 entries:
'n' => 1
'f' => 5
';' => 1
⋮
'0' => 1
'2' => 1
'3' => 1
'v' => 1
counts
The function counts is similar to countmap, but the result is a vector of frequencies. The important detail is that the first component of the output is the frequency of the smallest value, the second component is the frequency of the next integer, and so on.
julia> x = [1, 1, 2, 2, 3]
5-element Vector{Int64}:
1
1
2
2
3
julia> counts(x)
3-element Vector{Int64}:
2 # x내 1의 빈도
2 # x내 2의 빈도
1 # x내 3의 빈도
julia> y = [3, 5, 5, 8, 8, 8]
6-element Vector{Int64}:
3
5
5
8
8
8
julia> counts(y)
6-element Vector{Int64}:
1 # y내 3의 빈도
0 # y내 4의 빈도
2 # y내 5의 빈도
0 # y내 6의 빈도
0 # y내 7의 빈도
3 # y내 8의 빈도
You can specify the range (support) over which frequencies are measured.
# 정수 k만 입력하면 범위 1:k 내의 빈도수를 반환
julia> counts(x, 5)
5-element Vector{Int64}:
2
2
1
0
0
julia> counts(x, 0:5)
6-element Vector{Int64}:
0
2
2
1
0
0
Environment
- OS: Windows11
- Version: Julia 1.11.3, StatsBase v0.34.10
