Achal Neupane
Achal Neupane

Reputation: 5719

How to store character output from a loop and write as a text file in R?

We can work with data matrix very easily in R, but here I have character strings printed out from my loop as below:

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?
}

How can I save the my_string one after another leaving one line gap so I can write everything (collection) using the code below?

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

Upvotes: 1

Views: 434

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

You can use paste0() to concatenate each piece of the mylength string, separated by new lines:

collection <- ""

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

cat(collection)

Note that print() won't show those newlines, but cat should.

Upvotes: 1

Related Questions