R - how can I store the "print" value?

In R, when I use "print" I can see all the values, but how can I store this as a vector? For example, in a 'for': loop   for(i in 1:10)

, I would like to get the value of A when i = 1,2,3,4 ..... but if i use x=A

it only stores the final value of A, which is the value when i = 10. So how can I store the values ​​in print (A)? Also, I use several "for" loops, for example:

for (i in 1:9) {
  for (k in 1:4) {
  }
}

      

Hence, x [i] = A .. doesn't work very well here.

+2


a source to share


3 answers


I think Etiennebr's answer shows you what you should be doing, but here's how to capture the output print

as you say you want: use a function capture.output

.

> a <- capture.output({for(i in 1:5) print(i)})
> a
[1] "[1] 1" "[1] 2" "[1] 3" "[1] 4" "[1] 5"

      

You can see that it captures everything exactly as it is printed. To avoid all [1]

s, you can use cat

instead of printing:

a <- capture.output({for(i in 1:5) cat(i,"\n")})
> a
[1] "1 " "2 " "3 " "4 " "5 "

      



Once again, you probably don't really want to do this for your application, but there are situations where this approach is useful (for example, to hide the automatically typed text that some functions insist on).

EDIT: Since the output is print

or cat

is a string, if you captured it, it will still be a string and will have quotes. To remove quotes just use as.numeric

:

> as.numeric(a)
[1] 1 2 3 4 5

      

+4


a source


Perhaps you should use c()

.



a <- NULL
for(i in 1:10){
  a <- c(a,i)
}
print(a)

      

+1


a source


Another option could be the Reduce function:

a <- Reduce(function(w,add) c(w,add), NULL, 1:10)

      

0


a source







All Articles