0

我想将包含 R ( ) 的常用换行符的字符串写入\n数据库表的列中。

如何将新行转换为特定于操作系统的表示形式(Windows = CR/LF、Linux = LF、Mac = CR...)?

我了解到 R 不提供操作系统特定的表示,所以我必须找到一种解决方法:

任何打印/搜索字符串的尝试都失败了:

msg <- "I want to have \n a new line"
cat(msg)
# I want to have 
#  a new line

out <- capture.output(cat(msg))
out
# a vector with two elements (one for each row but no new line characters anymore)
# [1] "I want to have " " a new line"

paste(out, collapse = "\n")   # how could I inject the correct new line characters here?
# [1] "I want to have \n a new line"

# welcome endless-loop :-)

有什么方法可以让 R 从字符串中创建正确的换行符\n

PS:我正在使用内置tcltk包,puts但我总是以 R 将换行符“重新转换”为结尾\n......另一个“作弊”可能是\n用引号括起来以将其视为一行。到目前为止我不知道这如何工作......

4

2 回答 2

3

在 R 中正确设置新行代码的一种方法是查询操作系统。由于 OS X 和 Linux 的行为方式相同,因此这是一个确定操作系统是否为 Windows 的问题。一种方法是OS按如下方式询问环境变量。

if(substr(Sys.getenv("OS"),1,7) == "Windows") {
    # set Windows newline
  newLine <- "\r\n"
}
else {
    # set non-Windows newline
    newLine <- "\n"
}

接下来paste()newLine对象一起使用,由操作系统为换行生成正确的字符。

paste("my text string on a line",newline,sep="")

问候,

于 2017-11-25T02:54:15.173 回答
0

在这里,您可以找到我的最终实现作为已接受答案的可能替代方案:

# Returns the operating system specific new line character(s):
# CR LF on Windows, else only LF...
# Simlar to Microsofts .Net "Environment.NewLine"
platform.NewLine <- function() {

  is.windows <- grepl(tolower(.Platform$OS.type), "windows", fixed = TRUE)

  if (is.windows) {
    newline <- "\r\n"
  } else {
    newline <- "\n"
  }

  sys.name <- Sys.info()["sysname"]
  is.windows.2nd.opinion <- grepl(tolower(sys.name), "windows", fixed = TRUE)

  if (is.windows != is.windows.2nd.opinion)
    warning("R seems to run on Windows OS but this could not be recognized for sure")

  return(newline)
}

# Usage (examples) ------------------------------------------------------------------------------------------------

newline <- platform.NewLine()

# "print" shows the "symbolic" names (escape codes)
print(paste("Line1", "Line2", sep = newline))
# [1] "Line1\r\nLine2"
# uses "\n" or "\r\n" depending on your OS

# "cat" applies the newline escape codes to the output
cat(paste("Line1", "Line2", sep = newline))
# Line1
# Line2
于 2017-11-29T08:42:25.687 回答