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

如何基于含Frequency列的数据框创建计数列联表?

Solution for Creating Cross Tabulation with Frequency Column

Got it, let's figure out how to build that exact cross tab you need using your data frame with a Frequency column. I know you tried table(), xtabs(), and aggregate() but couldn't get it right—let's fix that with base R tools that work perfectly for this scenario.

Core Approach: Use xtabs() to Sum Frequency by Groups

The key here is telling R to sum the Frequency values across combinations of Hair and Eye categories, not just count rows. Here's the step-by-step code:

# Assume your data frame is named `df` (replace with your actual data frame name)
# Create the cross tabulation using Frequency as the value to aggregate
cross_tab <- xtabs(Frequency ~ Eye + Hair, data = df)

# Convert the contingency table to your desired data frame format
final_table <- as.data.frame.matrix(cross_tab)

Let's Test It with Your Example Data

If we use the HairEyeColor converted to a data frame:

HEC <- as.data.frame(HairEyeColor)
cross_tab <- xtabs(Frequency ~ Eye + Hair, data = HEC)
final_table <- as.data.frame.matrix(cross_tab)

# Optional: Reorder columns to match your exact desired output
final_table <- final_table[, c("Black", "Blond", "Brown", "Red")]
print(final_table)

This will output exactly the table you showed:

Black Blond Brown Red
Blue     20    94    84  17
Brown    68     7   119  26
Green     5    16    29  14
Hazel    15    10    54  14

Why This Works (And What You Might Have Missed)

  • xtabs() is designed for cross-tabulating weighted data (which is exactly what your Frequency column is). The formula Frequency ~ Eye + Hair tells R: "sum Frequency for every combination of Eye (rows) and Hair (columns)".
  • as.data.frame.matrix() converts the contingency table object from xtabs() into a standard data frame with columns as Hair categories and rows as Eye categories—just like your target table.

Alternative Base R Method: tapply()

If you prefer another base R approach, tapply() works too:

final_table <- as.data.frame(with(df, tapply(Frequency, list(Eye, Hair), sum)))
# Again, reorder columns if needed
final_table <- final_table[, c("Black", "Blond", "Brown", "Red")]

Both methods avoid plyr entirely and leverage base R tools to properly use your Frequency column instead of just counting rows.

内容的提问来源于stack exchange,提问作者Sciolism Apparently

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:52:40