是否有用於查找模式的內置功能?

在R中, mean()median()是標準函數,能夠完成您指望的操做。 mode()告訴您對象的內部存儲模式,而不是在其參數中出現最多的值。 可是是否有一個標準庫函數實現矢量(或列表)的統計模式? 函數


#1樓

給出全部按頻率排序的值的另外一個簡單選項是使用rlespa

df = as.data.frame(unclass(rle(sort(mySamples))))
df = df[order(-df$lengths),]
head(df)

#2樓

估計並相信如下連續函數是一種快速而骯髒的方法,用於估計您認爲來自連續單變量分佈(例如正態分佈)的數字向量的模式: code

estimate_mode <- function(x) {
  d <- density(x)
  d$x[which.max(d$y)]
}

而後得到模式估計: orm

x <- c(5.8, 5.6, 6.2, 4.1, 4.9, 2.4, 3.9, 1.8, 5.7, 3.2)
estimate_mode(x)
## 5.439788

#3樓

如下功能分爲三種形式: 對象

method =「 mode」 [默認值]:計算單峯向量的模式,不然返回NA
method =「 nmodes」:計算向量中的模式數
method =「 modes」:列出單峯或多峯向量的全部模式 排序

modeav <- function (x, method = "mode", na.rm = FALSE)
{
  x <- unlist(x)
  if (na.rm)
    x <- x[!is.na(x)]
  u <- unique(x)
  n <- length(u)
  #get frequencies of each of the unique values in the vector
  frequencies <- rep(0, n)
  for (i in seq_len(n)) {
    if (is.na(u[i])) {
      frequencies[i] <- sum(is.na(x))
    }
    else {
      frequencies[i] <- sum(x == u[i], na.rm = TRUE)
    }
  }
  #mode if a unimodal vector, else NA
  if (method == "mode" | is.na(method) | method == "")
  {return(ifelse(length(frequencies[frequencies==max(frequencies)])>1,NA,u[which.max(frequencies)]))}
  #number of modes
  if(method == "nmode" | method == "nmodes")
  {return(length(frequencies[frequencies==max(frequencies)]))}
  #list of all modes
  if (method == "modes" | method == "modevalues")
  {return(u[which(frequencies==max(frequencies), arr.ind = FALSE, useNames = FALSE)])}  
  #error trap the method
  warning("Warning: method not recognised.  Valid methods are 'mode' [default], 'nmodes' and 'modes'")
  return()
}

#4樓

抱歉,我可能會以爲太簡單了,但這不是嗎? (對於個人計算機上的1E6值,以1.3秒爲單位): ci

t0 <- Sys.time()
summary(as.factor(round(rnorm(1e6), 2)))[1]
Sys.time()-t0

您只需用向量替換「 round(rnorm(1e6),2)」。 get


#5樓

我目前沒法投票,但RasmusBååth的答案是我一直在尋找。 可是,我將對其進行一些修改,以限制分佈,例如僅在0到1之間的值。 it

estimate_mode <- function(x,from=min(x), to=max(x)) {
  d <- density(x, from=from, to=to)
  d$x[which.max(d$y)]
}

咱們知道您可能不想限制全部發行版,而後從=-「 BIG NUMBER」設置爲=「 BIG NUMBER」 io

相關文章
相關標籤/搜索