tags:

views:

110

answers:

3

in R , when i use "print", i can see all the values, but how can i save this as a vector for example, in for loop, for (i in 1:10), i want the value of A , when i= 1,2,3,4..... but if i use the x=A, it only have the final value of A which is the value when i = 10. so , how can i save the vaule in print(A).. BY THE WAY , I use more than one for loop it is like for (i in 1:9){ for (k in 1:4){ } } so, x[i]=A..do not work very good here

+1  A: 

Maybe you should use c().

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

Another option could be the function Reduce:

a <- Reduce(function(w,add) c(w,add), NULL, 1:10)
Karsten W.
+2  A: 

I think Etiennebr's answer shows you what you should do, but here is how to capture the output of print as you say you want: use the capture.output function.

> 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 printed. To avoid having all the [1]s, you can use cat instead of print:

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 when this approach is useful (eg. to hide automatically printed text that some functions insist on).

EDIT: Since the output of print or cat is a string, if you capture it, it still will be a string and will have quotation marks To remove the quotes, just use as.numeric:

> as.numeric(a)
[1] 1 2 3 4 5
Aniko
thx a lot ....thx for ur help...:)
alex
by the way ...is it possible to get rid of the quate mark as well??
alex
@alex: I have updated the answer to show how to remove quotes
Aniko
wow..that is amazing ..ok ...thx so much
alex