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

如何在R中统计问卷不同答案?寻求列名修改代码优化方案

Elegant Ways to Count Questionnaire Answer Frequencies (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 add Q_097 or remove Q_093 later.
  • Readability: Anyone reviewing your code can immediately understand what’s happening, instead of guessing what arbitrary column indices like 5:9 refer 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:23:16