Removing [1] with sink and sprintf output in R

风流意气都作罢 提交于 2019-12-07 16:18:45

问题


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")

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.

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

 [1] Hello World

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


回答1:


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

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

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.

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.



来源:https://stackoverflow.com/questions/17798330/removing-1-with-sink-and-sprintf-output-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!