我做了简单的循环并得到了打印结果,但不知道如何输出它。
这是我编码的:
>for (i in 0:45) for (j in 0:45) print(i/j)
[1] Inf
[1] 1
[1] 0.5
[1] 0.3333333
[1] 0.25
[1] 0.2
[1] 0.1666667
[1] 0.1428571
[1] 0.125
[1] 0.1111111
[1] 0.1
从这里开始,我该如何保存这个结果?我应该将 print (i/j) 放入对象中还是有其他方法将其保存到文件中?
谢谢你,
有几个选项,具体取决于什么output你要。
1) capture.output()
会将循环的输出抓取到文件中:
capture.output(for (i in 0:45) for (j in 0:45) print(i/j),
file = "foo.txt")
2)如果你想要数字,那么保存i/j
作为 R 对象save()
或作为文本文件(例如 csv)通过write.csv()
,不要打印它。
out <- c() ## NEVER write a loop like this! Always allocate storage & fill in
for(i in 0:45)
for(j in 0:45)
out <- c(out, i/j)
head(out)
save(out, "foo.rda")
write.csv(out, "foo.csv")
但是,您需要了解 R 中的向量化操作。在这种情况下,您可以使用以下方法更有效地执行通过两个循环在 R 中执行的操作:
out2 <- outer(0:45, 0:45, "/")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)