在R中存储table函数返回的频率及获取高低频值的方法
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

