寻找向量的统计模式:当有多个模式时 - return 最后一个模式
Finding the statistical mode of a vector: When having more than single mode — return the last mode
计算一个向量的统计众数时,往往有不止一种众数:
c(1, 1, 2, 2, 3, 4) # mode is both 1 and 2
在这种情况下,如果我想在两个(或更多)可能的值之间做出决定,我使用 {collapse}
包中的 fmode()
,它通过 ties
参数提供, 3 种可能的决定方法:
ties
an integer or character string specifying the method to resolve ties between multiple possible > modes i.e. multiple values with the maximum frequency or sum of weights:
Int.
String
Description
1
first
take the first occurring mode.
2
min
take the smallest of the possible modes.
3
max
take the largest of the possible modes.
fmode()
的例子
library(collapse)
my_vec <- c(1, 1, 3, 4, 5, 5, -6, -6, 2, 2) # 4 modes here: 1, 2, 5, -3
fmode(my_vec, ties = "first")
#> [1] 1
fmode(my_vec, ties = "min")
#> [1] -6
fmode(my_vec, ties = "max")
#> [1] 5
我的问题
我正在寻找一种“最后”方法——即,只要有不止一种模式,return“最后”模式。但不幸的是,fmode()
没有 "last"
方法。
所以如果我们 return 我的例子,我希望的是向量:
my_vec <- c(1, 1, 3, 4, 5, 5, -6, -6, 2, 2)
我想要一个功能
custom_mode_func(my_vec, method = "last")
## [1] 2
您对折叠的唯一选择是预先对数据进行排序,例如
library(collapse)
my_vec <- c(1, 1, 3, 4, 5, 5, -6, -6, 2, 2)
data.frame(v = my_vec, g = gl(2, 5)) %>%
roworder(g) %>%
tfm(t = data.table::rowid(g)) %>%
roworder(g, -t) %>%
gby(g) %>%
smr(last = fmode(v, ties = "first"))
之所以rev
不行,是因为collapse grouping不对数据进行拆分,只是判断一行属于哪个组,然后用[=21=对所有组同时统计] C++ 中的算法(例如,分组计算由 fmode
本身完成)。所以在你的代码中 rev
实际上是在分组之前执行并反转整个向量。在这种情况下,可能最快的解决方案是直接调用 fmode.default
(以优化方法分派)的本机 data.table 实现。如果有时间,我可以考虑添加 "last"
模式。
计算一个向量的统计众数时,往往有不止一种众数:
c(1, 1, 2, 2, 3, 4) # mode is both 1 and 2
在这种情况下,如果我想在两个(或更多)可能的值之间做出决定,我使用 {collapse}
包中的 fmode()
,它通过 ties
参数提供, 3 种可能的决定方法:
ties
an integer or character string specifying the method to resolve ties between multiple possible > modes i.e. multiple values with the maximum frequency or sum of weights:
Int. String Description 1 first take the first occurring mode. 2 min take the smallest of the possible modes. 3 max take the largest of the possible modes.
fmode()
的例子
library(collapse)
my_vec <- c(1, 1, 3, 4, 5, 5, -6, -6, 2, 2) # 4 modes here: 1, 2, 5, -3
fmode(my_vec, ties = "first")
#> [1] 1
fmode(my_vec, ties = "min")
#> [1] -6
fmode(my_vec, ties = "max")
#> [1] 5
我的问题
我正在寻找一种“最后”方法——即,只要有不止一种模式,return“最后”模式。但不幸的是,fmode()
没有 "last"
方法。
所以如果我们 return 我的例子,我希望的是向量:
my_vec <- c(1, 1, 3, 4, 5, 5, -6, -6, 2, 2)
我想要一个功能
custom_mode_func(my_vec, method = "last")
## [1] 2
您对折叠的唯一选择是预先对数据进行排序,例如
library(collapse)
my_vec <- c(1, 1, 3, 4, 5, 5, -6, -6, 2, 2)
data.frame(v = my_vec, g = gl(2, 5)) %>%
roworder(g) %>%
tfm(t = data.table::rowid(g)) %>%
roworder(g, -t) %>%
gby(g) %>%
smr(last = fmode(v, ties = "first"))
之所以rev
不行,是因为collapse grouping不对数据进行拆分,只是判断一行属于哪个组,然后用[=21=对所有组同时统计] C++ 中的算法(例如,分组计算由 fmode
本身完成)。所以在你的代码中 rev
实际上是在分组之前执行并反转整个向量。在这种情况下,可能最快的解决方案是直接调用 fmode.default
(以优化方法分派)的本机 data.table 实现。如果有时间,我可以考虑添加 "last"
模式。