gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:58:29 25 4
gpt4 key购买 nike

我有一个数组

a <- c(1,1,1,1,1,2,3,4,5,5,5,5,5,6,7,7,7,7)

我想使用一些命令来告诉我数组中出现频率最高的数字是哪个?

有一个简单的命令吗?

最佳答案

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"

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

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

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

sort(table(a)[table(a) > 1])
# a
# 7 1 5
# 4 5 5

关于r - 使用 R 计算数组中出现的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13841599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com