I did simple loop and got the result in print but not sure how to output it.
This is what I coded:
>for (i in 0:45) for (j in 0:45) print(i/j)
[1] Inf
[1] 1
[1] 0.5
[1] 0.3333333
[1] 0.25
[1] 0.2
[1] 0.1666667
[1] 0.1428571
[1] 0.125
[1] 0.1111111
[1] 0.1
From here, how can i save this outcome? Should I make print (i/j) into an object or is there other way to save it into a file? thank you,
A couple of options, depending on what output you want.
1)
capture.output()
will grab the output of the loop into a file:2) if you want the numbers, then save the
i/j
either as an R object viasave()
or as a text file (e.g. csv) viawrite.csv()
, don't print it.However, you need to learn about vectorising operations in R. The sort of operation you are doing in R via two loops can be conducted more efficiently in this case using:
I just happen to have a function opened that writes to a file. I used sink() (see DWin's and Gavin's answer for other solutions)
Which produces a file (this is only the head):
It really depends on what your want to do. If you just want to capture output into a text file then one of
capture.output
,cat
, orsink
are the functions to look at. If you what to create an R object for later use in a session, then create an object with the desired structure: vector, list, matrix, or data.frame. Objects are then saved with thesave
function. Text representations of objects can be created withdput
ordump
.