如何在R中对长错误、消息换行且不删除空格?
在R中优化长消息代码格式且不丢失空格的方法
问题描述
为优化代码样式,需要对R中过长的消息进行换行处理,但不能删除原有空格。示例代码及问题如下:
# fun with long message lng_mes <- function() { message("This is a very long message and it goes on and on and on and it makes my code look terrible because it is so long and it stretches way out into the page") } # 运行时控制台会自动换行,内容正常 lng_mes() # 尝试用strwrap换行优化代码格式 lng_mes2 <- function() { message(strwrap("This is a very long message and it goes on and on and on and it makes my code look terrible because it is so long and it stretches way out into the page")) } # 运行后部分空格丢失 lng_mes2()
lng_mes2()的输出出现空格丢失:
This is a very long message and it goes on and on and on andit makes my code look terrible because it is so long and itstretches way out into the page
解决方法
方法1:用paste0拼接多行字符串
将长消息拆分为多行,通过paste0直接拼接,既实现代码换行,又完全保留原始空格:
lng_mes3 <- function() { message(paste0( "This is a very long message and it goes on and on and on and ", "it makes my code look terrible because it is so long and it ", "stretches way out into the page" )) } lng_mes3()
方法2:用stringr::str_flatten拼接向量
如果已将消息拆分为多行向量,使用stringr包的str_flatten直接拼接,不会修改原有空格:
library(stringr) lng_mes4 <- function() { msg_lines <- c( "This is a very long message and it goes on and on and on and ", "it makes my code look terrible because it is so long and it ", "stretches way out into the page" ) message(str_flatten(msg_lines)) } lng_mes4()
方法3:利用R 4.1.0+的多行字符串特性
R 4.1.0及以上版本支持用"""定义多行字符串,只要内部每行的空格与原始内容一致,就能完美保留格式:
lng_mes5 <- function() { message(""" This is a very long message and it goes on and on and on and it makes my code look terrible because it is so long and it stretches way out into the page """) } lng_mes5()
注:若要让代码缩进对齐,需确保多行字符串内部的换行和空格与原始消息完全匹配,避免引入多余空格。
内容的提问来源于stack exchange,提问作者ifoxfoot
相关产品推荐
相关产品推荐

