使用特定于操作系统的换行符(CRLF、LF、CR)构建字符串以将其写入数据库表列 [英] Build string with OS-specific newline characters (CRLF, LF, CR) to write it into a database table column

查看:59
本文介绍了使用特定于操作系统的换行符(CRLF、LF、CR)构建字符串以将其写入数据库表列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to write write a string that contains the usual new line character of R (\n) into a column of a database table.

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

How can I convert the new line into operating system specific representation (Windows = CR/LF, Linux = LF, Mac = CR...)?

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

I have learned that R does not provide the operating system specific representation so I have to find a work-around:

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

Any trial to print/cat the string did fail:

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 创建正确的换行符?

Is there any way to let R create the correct new line characters from \n in a string?

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

PS: I am playing around with the built-in tcltk package and puts but I always end with R "reconverting" the newline into \n... Another "cheat" could be to enclose the \n with quotation marks to read it as if it were one line. I have no idea so far how this could work...

推荐答案

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

One way to correctly set the new line code in R is to query the operating system. Since both OS X and Linux behave the same way, it's a question of determining whether the operating system is Windows. One way to do this is to interrogate the OS environment variable as follows.

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

接下来使用 paste()newLine 对象来通过操作系统为新行生成正确的字符.

Next use paste() with the newLine object to generate the right characters for new line by operating system.

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

问候,

这篇关于使用特定于操作系统的换行符(CRLF、LF、CR)构建字符串以将其写入数据库表列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆