在 R 中使用 sink 和 sprintf 输出删除 [1] [英] Removing [1] with sink and sprintf output in R

查看:44
本文介绍了在 R 中使用 sink 和 sprintf 输出删除 [1]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 sprintf 和 sink 编写一系列字符和数值:

I am trying to write a series of characters and numerical values using sprintf and sink:

 sink("sample.txt", append=TRUE, split=TRUE)
 sprintf("Hello World")

当然,上面是一个例子,所以我没有上面数据框的数值,但我需要使用sprintf.

of course, the above is an example, so I don't have the numerical values from a data frame above, but I need to use sprintf.

文本文件 (sample.txt) 中的输出如下所示:

The output in the text file (sample.txt) looks like this:

 [1] Hello World

如何从行中删除 [1]?有没有办法让 [1] 不写入文件?

How do I remove the [1] from the line? Is there a way so the [1] won't write to the file?

推荐答案

想到两个选项,使用 cat()writeLines()

Two options spring to mind, using cat() or writeLines()

> cat(sprintf("Hello World"), "\n")
Hello World 
> writeLines(sprintf("Hello World"))
Hello World

您遇到的问题是 sprintf() 返回一个字符向量,并且与任何其他字符向量一样,如果您 print ,R 会像向量一样打印它.您想要的是包含在字符向量的第一个元素中的字符串(在这种情况下是唯一的一个).因此我们使用工具来写出字符串而不是打印字符向量.

The problem you have is that sprintf() returns a character vector and like any other character vector R prints it like a vector if you print it. What you want is the string contained with the first element of the character vector (the only one in this case). Hence we use tools to write out the string not print the character vector.

请注意,这两者都可以通过 file 参数(在 cat() 中)或 con 参数(在writeLines()),你可能会觉得它很有用.

Note that both these can write directly to a file via the file argument (in cat()) or the con argument (in writeLines()), which you may find useful.

这篇关于在 R 中使用 sink 和 sprintf 输出删除 [1]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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