将长度为一个字符转换为一字节字符串

发布于 2024-12-01 03:16:39 字数 436 浏览 0 评论 0原文

好吧,我承认这个标题有点误导。我目前脑死亡,所以我可能在这里遗漏了一些明显的东西。

我正在开发 R 驱动的 web 应用程序,我想将某些参数传递给 read.table 函数 - sep 等。如果我将单字节字符作为 sep 参数传递,那么一切都会像魅力一样工作:,, ;, |...但是如果我尝试传递 \t ,则会收到错误:

invalid 'sep' value: must be one byte

当然,发生这种情况是因为 \t 实际上被转义了 (\\t )。我是否有机会转义,并“按原样”传递它 - 即单字节字符串?

OK, I admit that the title is a bit misleading. I'm braindead currently, so I may be missing something obvious here.

I'm working on R-powered webapp, and I'd like to pass certain parameters to read.table function - sep among others. Everything works like a charm if I'm passing single-byte characters as sep argument: ,, ;, |... but if I try to pass \t, I get an error:

invalid 'sep' value: must be one byte

of course, this happens because \t is actually escaped (\\t). Is there any chance that I can escape escapes, and pass it "as is" - i.e. a single byte string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〆一缕阳光ご 2024-12-08 03:16:39

您需要将 sep="\t" 作为参数写入 read.table

对于制表符,t 会被转义。换句话说,您告诉 R t 并不真正意味着 t,而是 tab。如果您使用 \\ 转义 \,那么您就是在告诉 R,\ 并不真正意味着 转义 而是文字 \

下面是一些代码,说明了 read.tablesep="\t" 的正确用法。只是为了好玩,我使用 textConnection 使用连接进行写入和读取,而不是使用磁盘上的文件:

# Create a tab delimited file
zz <- textConnection("foo", "w")
write.table(matrix(1:12, ncol=3), file=zz, sep="\t")
close(zz)
foo

# The simple way:
tabsep <- "\t"

# The hard way, or if data was passed from a web app and you need to clean it
tabsep <- gsub("\\\\t", "\t", "\\t")


# Read a tab delimited file
zz <- textConnection(foo)
read.table(zz, sep=tabsep)
close(zz)

这会产生以下输出:

  V1 V2 V3
1  1  5  9
2  2  6 10
3  3  7 11
4  4  8 12

You need to write sep="\t" as the parameter to read.table.

In the case of a tab, it is the t that gets escaped. In other words, you are telling R that t doesn't really mean t, but tab. If you escape the \, by using \\ then you are telling R that the \ doesn't really mean escape but a literal \.

Here is some code illustrating the correct usage of sep="\t" in read.table. And just for the fun of it, I use textConnection to use a connection to write to and read from, rather than using a file on disk:

# Create a tab delimited file
zz <- textConnection("foo", "w")
write.table(matrix(1:12, ncol=3), file=zz, sep="\t")
close(zz)
foo

# The simple way:
tabsep <- "\t"

# The hard way, or if data was passed from a web app and you need to clean it
tabsep <- gsub("\\\\t", "\t", "\\t")


# Read a tab delimited file
zz <- textConnection(foo)
read.table(zz, sep=tabsep)
close(zz)

This produces the following output:

  V1 V2 V3
1  1  5  9
2  2  6 10
3  3  7 11
4  4  8 12
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文