开发者

R - how can I save the value of "print"?

开发者 https://www.devze.com 2022-12-27 22:00 出处:网络
In R , when I use \"print\", I can see all the values, but how ca开发者_高级运维n I save this as a vector?

In R , when I use "print", I can see all the values, but how ca开发者_高级运维n I save this as a vector? For example, in a 'for' loop: for(i in 1:10), I would like the value of A , when i= 1,2,3,4..... but if I use x=A, it only saves the final value of A which is the value when i = 10. So, how can I save the values in print(A)? Additionally, I use more than one 'for' loop e.g.:

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

Consequently, x[i]=A..does not work very well here.


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


Maybe you should use c().

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


Another option could be the function Reduce:

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

精彩评论

暂无评论...
验证码 换一张
取 消