如何在R语言中将列数据转换为段落形式输出?
问题描述
我有一个名为df的数据集(如下所示),包含多列数据。我希望将所有列拼接起来,逐行输出单个段落,格式如预期输出所示,使用\r\n作为换行语法生成段落。
导入数据代码
library(tibble) df <- tibble(ID = c(001, 002, 003, 004), resp = c("this is the response of the subject one... \r\n and more and more...", "Host: this is the response of the subject two", "now a response from subejct three", "that is a different one, \r\n and it is from subject 4"), comment = c("now a comment from the assessor", NA, "No comments", "I don't agree with this comment"))
输入数据
# A tibble: 4 × 3 ID resp comment <dbl> <chr> <chr> 1 1 this is the response of the subject one now a comment from the assessor 2 2 this is the response of the subject two NA 3 3 now a response from subejct three No comments 4 4 that is a different one, and it is from subject 4 I don't agree with this comment
解决方案
使用dplyr和stringr包处理格式,步骤如下:
- 将ID格式化为三位数字(补前导零);
- 把
resp中的\r\n替换为换行加缩进,保证换行后的内容对齐; - 处理NA值,将其替换为字符串"NA";
- 逐行构建符合要求的段落文本,最后合并所有段落。
library(dplyr) library(stringr) # 格式化每行内容 formatted_paragraphs <- df %>% mutate( ID = str_pad(ID, width = 3, pad = "0"), resp = str_replace_all(resp, "\\r\\n ", "\r\n "), comment = ifelse(is.na(comment), "NA", comment), paragraph = str_glue("Participant: {ID}\r\nResponse: {resp}\r\nComment: {comment}\r\n") ) %>% pull(paragraph) # 合并成最终输出文本 final_text <- paste0("\r\n", paste(formatted_paragraphs, collapse = "\r\n"), " ") # 打印查看结果 cat(final_text)
预期输出
" Participant: 001 Response: this is the response of the subject one... and more and more... Comment: now a comment from the assessor Participant: 002 Response: Host: this is the response of the subject two Comment: NA Participant: 003 Response: now a response from subejct three Comment: No comments Participant: 004 Response: that is a different one, and it is from subject 4 Comment: I don't agree with this comment "
内容的提问来源于stack exchange,提问作者Ruam Pimentel
相关产品推荐
相关产品推荐

