R-如何保存“打印"的值? [英] R - how can I save the value of "print"?

查看:51
本文介绍了R-如何保存“打印"的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,当我使用"print"时,我可以看到所有值,但是如何将其保存为矢量?例如,在"for"循环中: for(i在1:10中),当i = 1,2,3,4 .....但我使用 x = A <时,我想要A的值/code>,它仅保存A的最终值,即i = 10时的值.那么,如何将这些值保存在print(A)中?此外,我使用了多个"for"循环,例如:

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) {
  }
}

因此,x [i] = A ..在这里不能很好地工作.

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

推荐答案

我认为Etiennebr的答案向您展示了您应该做的事情,但这是如何按您的意愿捕获 print 的输出:使用 capture.output 函数.

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"

您可以看到它完全捕获了打印的所有内容.为避免使用所有 [1] ,可以使用 cat 代替打印:

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).

由于 print cat 的输出是字符串,因此,如果捕获它,它仍将是字符串并且将带有引号.要删除引号,只需使用 as.numeric :

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

这篇关于R-如何保存“打印"的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆