You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中存储table函数返回的频率及获取高低频值的方法

Extracting Frequencies from table() in R

Got it, let's walk through exactly what you need to do here—super straightforward once you know the tricks!

Step 1: Store All Frequency Values from table()

When you run table(nums), it returns a table object that maps each unique number to its count. To grab all those frequency values and store them for later use, you just need to convert the table to a numeric vector. Here's how:

# Your example vector
nums <- c(5,2,5,9,2)
# Generate the frequency table
freq_table <- table(nums)
# Extract and store all frequency values
all_frequencies <- as.vector(freq_table)

# Alternatively, you can directly subset the table to get the values:
# all_frequencies <- freq_table[]

For your example, all_frequencies will be c(2, 2, 1)—these are the counts for 5, 2, and 9 respectively.

Step 2: Get Highest and Second-Highest Frequencies

Once you have the frequency values, sorting them in descending order lets you easily pick the top two values. Here's the code:

# Sort frequencies from highest to lowest
sorted_freqs <- sort(all_frequencies, decreasing = TRUE)

# Grab the highest frequency
highest_freq <- sorted_freqs[1]
# Grab the second-highest frequency
second_highest_freq <- sorted_freqs[2]

In your example, sorted_freqs becomes c(2, 2, 1), so both highest_freq and second_highest_freq will be 2—which makes sense since both 5 and 2 appear twice.

Bonus: Skip the Vector Conversion (Optional)

You can actually sort the table object directly without converting it to a vector first. This works because R's sort() function handles table objects nicely:

sorted_freq_table <- sort(freq_table, decreasing = TRUE)
highest_freq <- sorted_freq_table[1]
second_highest_freq <- sorted_freq_table[2]

This gives you the same result, and you still have the mapping of numbers to counts if you need it later.

内容的提问来源于stack exchange,提问作者Michael Agarenzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:00:24