我想写一个字符串,其中包含R(\n
)的常用新行字符到数据库表的列中。
如何将新行转换为特定于操作系统的表示形式(Windows = CR / LF,Linux = LF,Mac = CR ...)?
我了解到R没有提供特定于操作系统的表示,所以我必须找到一个解决方法:
任何打印/ cat字符串的试验都会失败:
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&#34; resverting&#34;结束。新行到\n
...
另一个&#34;作弊&#34;可以用引号括起\n
来读取它,好像它是一行一样。到目前为止我不知道这是如何起作用的......
答案 0 :(得分:1)
在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="")
的问候,
Len
答案 1 :(得分: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