如何在R语言生成的三维交叉表中纳入统计计数?
Hey there! I see exactly where you're stuck—when you use table() on your grouped 3waydata, it's just counting how many times each duration/education/sex combo appears in that data frame (which is 1 for each, since you already grouped and summarised), not pulling in your calculated count values. Let's fix that with the right tool for the job: xtabs().
Step-by-Step Solution
Your 3waydata is already perfectly structured for this—you just need to tell R to use your count column as the weight for the cross-tabulation. Here's how:
# Use xtabs to build the 3-way table with your custom counts three_way_table <- xtabs(count ~ duration + sex + education, data = 3waydata) # Optional: Convert to a standard table object if needed three_way_table <- as.table(three_way_table)
Why This Works
The xtabs() function is built specifically for creating contingency tables from pre-summarized data. The formula count ~ duration + sex + education tells R:
- Use the
countvalues to fill the table cells - Cross-tabulate using
duration,sex, andeducationas the three dimensions
Example to Test
Let’s use sample data to demonstrate how this comes together:
library(dplyr) # Sample input data data <- data.frame( duration = c("short", "long", "short", "long", "short"), education = c("high", "low", "high", "low", "medium"), sex = c("M", "F", "M", "F", "F"), number = c(5, 3, 2, 4, 6) ) # Your existing grouping/summarizing code 3waydata <- data %>% group_by(duration, education, sex) %>% summarise(count = sum(number), .groups = "drop")
Running the xtabs() code above will generate a 3-way table where each cell holds the sum of number for that combination, not just a row count.
Bonus: Make the Table More Readable
If you want a flattened, easier-to-read output of your 3-way table, wrap the result in ftable():
ftable(three_way_table)
This will print the table in a compact format that’s simpler to parse than the default array structure.
内容的提问来源于stack exchange,提问作者user8132864

