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

R实现导出SPSS开放式问卷回答为按问题分组的文本文件

R实现SPSS开放式调研问题按列导出功能

背景

我有存储为SPSS .sav格式的调研结果,其中部分调研问题为开放式,受访者可自行输入回答。在SPSS中只需选中一个或多个列,即可将回答导出为文本文件,导出内容按每个问题(对应列内容)分组,各回答之间以空行分隔。该文本文件后续可用于给文本中的短语或句子分配编码的主题分析。

我在R中似乎找不到实现相同功能的简便方法,所有常用导出格式的输出都是表格形式,在RStudio中选中列得到的文本输出是按受访者而非按列分组的。

示例数据

library(labelled)
library(tidyverse)

comments<-tibble(
  shakey=as.character(c("To be or not to be", "", "Alas poor Yorick", "", "Is this a dagger that I see before me?", "A rose by any other name")), 
  versey=as.character(c("", "The boy stood on the burning deck", "", "Oft in the stilly night", "", "Lars Porsena of Clusium, by the nine gods he swore"))
  )

var_label(comments$shakey)<-"Can you quote some Shakespeare?"
var_label(comments$versey)<-"Can you quote some poetry?"

期望输出效果

*Can you quote some Shakespeare?*

To be or not to be

Alas poor Yorick

Is this a dagger that I see before me?

A rose by any other name

*Can you quote some poetry?*

The boy stood on the burning deck

Oft in the stilly night

Lars Porsena of Clusium, by the nine gods he swore

要求以列标签为标题,每列的非空回答依次排列,互相之间以空行分隔。

现有方案的不足

我目前写出的最接近目标效果的代码是:

comlong<-pivot_longer(comments, everything(),
                     names_to="question",
                     values_to="response") %>%
  arrange(question) %>% 
  filter(response!="")

虽然该代码可以将所有回答汇总到单列中,但还需要一定编辑才能得到上述目标格式,在数据量较大时操作成本很高。

最终解决方案

调整Akrun提出的新增summarise代码行的方案后即可得到和SPSS高度相似的输出:

comments %>%
  summarise(across(everything(), ~ c(paste0(sprintf('**%s**', cur_column()), "

", sprintf('*%s*', var_label(.))), .))) %>%
  pivot_longer(cols = everything(), 
               names_to = 'question', 
               values_to = 'response') %>% 
  arrange(question) %>% 
  filter(response != '') %>% 
  select(response) %>% 
  write.table("comments.md",quote=FALSE, eol="

", row.names=FALSE, col.names=FALSE)

该代码会同时插入列名和列标签(部分场景下列标签的描述性不足时可直接参考列名),输出为markdown文件,可直接导入Qualcoder等工具中进行主题编码。若需要文字处理格式的输出,运行如下命令:

pandoc comments.md -o comments.odt

即可生成odt格式的文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:09:00