如何在R中对factor型Estrato列分组并与Callevive列生成列联表
Estrato and Create Contingency Table with Callevive Hey there! Let's work through this task together. Here's a step-by-step approach to get the result you need:
1. Subset the first 25 rows
First, let's extract the first 25 rows of your dataframe to work with:
# Grab the first 25 rows of datos17 datos_subset <- head(datos17, 25)
2. Group the Estrato column
We'll categorize the factor values into low, medium, high, and 其他 (other) groups. I'll show you two common methods—pick the one that fits your workflow:
Option 1: Using dplyr (tidyverse style)
This method is clean and readable, especially if you're already using the tidyverse:
# Load the dplyr package if you haven't already library(dplyr) # Create the grouped Estrato column datos_subset <- datos_subset %>% mutate(Estrato_grouped = case_when( Estrato %in% c(1, 2) ~ "low", Estrato %in% c(3, 4, 5) ~ "medium", Estrato == 6 ~ "high", TRUE ~ "其他" # Catch-all for any unlisted values ))
Option 2: Using base R
If you prefer not to load extra packages, use nested ifelse():
# Create the grouped column with base R functions datos_subset$Estrato_grouped <- with(datos_subset, ifelse(Estrato %in% c(1, 2), "low", ifelse(Estrato %in% c(3, 4, 5), "medium", ifelse(Estrato == 6, "high", "其他"))) )
3. Generate the contingency table
Now we'll create the cross-tabulation between our grouped Estrato and Callevive. Again, two options for presentation:
Option 1: Basic base R table
This gives a simple, standard contingency table:
# Create and print the table contingency_table <- table(datos_subset$Estrato_grouped, datos_subset$Callevive) print(contingency_table)
Option 2: Formatted table with janitor
For a more polished, human-readable table with optional totals, use the janitor package:
# Load janitor if needed library(janitor) # Create a formatted table with row/column totals datos_subset %>% tabyl(Estrato_grouped, Callevive) %>% adorn_totals(c("row", "col")) # Remove this line if you don't want totals
That's it! After running these steps, you'll have the grouped column and contingency table matching your requirements.
内容的提问来源于stack exchange,提问作者Jonas

