如何存储循环中的字符输出并在R中写为文本文件?

时间:2017-09-25 02:16:02

标签: r

我们可以很容易地在R中处理数据矩阵,但是在这里我从我的循环中打印出字符串,如下所示:

for (i in 1:length(mylength)){
DO something to get my_string until length(mylength)
cat(my_string)
collection <-  ##how can I save the my_string one after another leaving one line gap so I can write everything (collection) using the code below?
}

如何一个接一个地保存my_string,留下一个行间隙,以便我可以使用下面的代码编写所有内容(collection)?

##writing the collected file
cat(collection, file= "All_colected_mystring.txt")

1 个答案:

答案 0 :(得分:1)

您可以使用paste0()连接mylength字符串的每一部分,用新行分隔:

collection <- ""

for (i in 1:length(mylength)) {
    # get my_string
    collection <- paste0(collection, "\n")
}

cat(collection)

请注意,print()不会显示这些换行符,但cat应该显示。