使用R计算数组中出现的频率

use*_*765 10 r

我有一个阵列

a <- c(1,1,1,1,1,2,3,4,5,5,5,5,5,6,7,7,7,7)
Run Code Online (Sandbox Code Playgroud)

我想用一些命令告诉我哪个是数组中最常用的数字?

有一个简单的命令吗?

A5C*_*2T1 26

table()功能足以满足这一要求,如果您的数据有多种模式,这项功能特别有用.

考虑以下选项,所有选项都与table()和相关max().


# Your vector
a = c(1,1,1,1,1,2,3,4,5,5,5,5,5,6,7,7,7,7)

# Basic frequency table
table(a)
# a
# 1 2 3 4 5 6 7 
# 5 1 1 1 5 1 4 

# Only gives me the value for highest frequency
# Doesn't tell me which number that is though
max(table(a))
# [1] 5

# Gives me a logical vector, which might be useful
# but not what you're asking for in this question
table(a) == max(table(a))
# a
#    1     2     3     4     5     6     7 
# TRUE FALSE FALSE FALSE  TRUE FALSE FALSE 

# This is probably more like what you're looking for
which(table(a) == max(table(a)))
# 1 5 
# 1 5 

# Or, maybe this
names(which(table(a) == max(table(a))))
# [1] "1" "5"
Run Code Online (Sandbox Code Playgroud)

如评论中所示,在某些情况下,您可能希望查看两个或三个最常出现的值,在这种情况下sort()很有用:

sort(table(a))
# a
# 2 3 4 6 7 1 5 
# 1 1 1 1 4 5 5 
Run Code Online (Sandbox Code Playgroud)

您还可以设置要在表中返回的值的阈值.例如,如果您只想返回多次出现的数字:

sort(table(a)[table(a) > 1])
# a
# 7 1 5 
# 4 5 5 
Run Code Online (Sandbox Code Playgroud)


Rui*_*ira 5

使用table()功能:

## Your vector:
a <- c(1,1,1,1,1,2,3,4,5,5,5,5,5,6,7,7,7,7)

## Frequency table
> counts <- table(a)

## The most frequent and its value
> counts[which.max(counts)]
# 1
# 5

## Or simply the most frequent
> names(counts)[which.max(counts)]
# [1] "1"
Run Code Online (Sandbox Code Playgroud)