如何在R中统计问卷不同答案?寻求列名修改代码优化方案
Great question—hardcoding column numbers is definitely brittle, especially if your questionnaire ever adds or removes questions later. Let’s look at a couple of concise, flexible approaches that work regardless of how many Q_* columns you have in your data frame DS.
Method 1: Tidyverse (dplyr + tidyr) – Most Readable
This approach reshapes your data to long format first, then counts responses across all questions in one go. It’s intuitive and easy to extend:
library(dplyr) library(tidyr) # Pivot all Q_* columns to long format, then count each answer response_counts <- DS %>% select(starts_with("Q_")) %>% # Auto-grab all question columns (no hardcoding!) pivot_longer(everything(), names_to = "question", values_to = "answer") %>% count(question, answer, name = "count") %>% # Optional: Map numeric codes to labels if needed mutate(answer_label = case_when( answer == 1 ~ "a", answer == 2 ~ "b", # Add more mappings as required TRUE ~ as.character(answer) ))
Method 2: Base R – No External Packages
If you prefer sticking to base R, use lapply to iterate over question columns and combine results cleanly:
# Get all question columns using regex question_cols <- grep("^Q_", colnames(DS), value = TRUE) # Calculate counts for each column and merge into a single data frame response_counts <- do.call(rbind, lapply(question_cols, function(col) { tab <- table(DS[[col]]) data.frame( question = col, answer = as.integer(names(tab)), count = as.integer(tab) ) })) # Optional: Add answer labels response_counts$answer_label <- factor(response_counts$answer, levels = c(1,2), labels = c("a","b"))
Why These Are Better Than Fixed Column Numbers
- Flexibility: Both methods automatically detect all columns starting with
Q_, so you won’t need to update code if you addQ_097or removeQ_093later. - Readability: Anyone reviewing your code can immediately understand what’s happening, instead of guessing what arbitrary column indices like
5:9refer to. - Scalability: Works seamlessly for 5 questions or 500 without changing a single line of code.
If you had a specific conta_respo... code snippet you were working with, feel free to share it and we can refine these approaches even further!
内容的提问来源于stack exchange,提问作者rmaranhao

