R - how can I save the value of “print”?

佐手、 提交于 2020-01-02 14:01:08

问题


In R , when I use "print", I can see all the values, but how can 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.


回答1:


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



回答2:


Maybe you should use c().

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



回答3:


Another option could be the function Reduce:

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


来源:https://stackoverflow.com/questions/2667478/r-how-can-i-save-the-value-of-print

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!