如何在R语言的sprintf()中去除输出的\n换行符?
去除R语言sprintf输出中的换行符\n
方案1:生成阶段避免多余换行
你当前的代码里,格式字符串每行末尾的\n加上代码换行后的缩进,导致输出出现连续换行和大量冗余空格。可以调整格式字符串的写法,从根源上避免生成\n:
# 写法1:将格式字符串合并为一行,直接去掉所有\n question <- sprintf("Can you interpret the results : Threshold: %f Sensitivity: %f Specificity: %f PPV: %f NPV: %f Accuracy: %f", roc_table$threshold, roc_table$sensitivity, roc_table$specificty, roc_table$ppv, roc_table$npv, roc_table$accuracy) # 写法2:用paste拼接格式字符串,既保留代码可读性,又不生成\n question <- sprintf(paste("Can you interpret the results :", "Threshold: %f", "Sensitivity: %f", "Specificity: %f", "PPV: %f", "NPV: %f", "Accuracy: %f", sep = " "), roc_table$threshold, roc_table$sensitivity, roc_table$specificty, roc_table$ppv, roc_table$npv, roc_table$accuracy)
方案2:生成后清除已有的\n
如果已经得到了带\n的字符串,用基础R的gsub或者stringr工具包来批量替换:
# 基础R方法:直接替换所有\n为空字符 clean_question <- gsub("\n", "", question) # 若同时要清除冗余空格(比如输出里的大量缩进空格),可以一步到位 clean_question <- gsub("\\s+", " ", gsub("\n", "", question))
如果习惯用stringr包(需先安装并加载):
library(stringr) # 移除所有\n clean_question <- str_remove_all(question, "\n") # 同时移除\n和多余空格 clean_question <- str_squish(str_remove_all(question, "\n"))
内容的提问来源于stack exchange,提问作者Kodex
相关产品推荐
相关产品推荐

