将for循环的结果另存为r中的向量 [英] Saving results from for loop as a vector in r
问题描述
我有以下for循环,可打印从1到10的数字:
I have the following for loop which prints numbers from 1 to 10:
for (i in 1:10) {print (i) }
如何将结果另存为矢量,而不是仅将其打印到控制台?
How do I save the results as a vector, instead of just printing them to the console?
如果我尝试:
my_vector <- for (i in 1:10) {print (i) }
然后致电my_vector
,我得到:
NULL
推荐答案
调用print
始终会将每次迭代的结果打印到控制台.如果保留print
命令,则可能会得到不需要的输出.
Calling print
will always print the result of each iteration to the console. If you leave in the print
command, then you might get unwanted output.
您的主要问题是您没有在for
循环之前初始化my_vector
.相反,您可以执行以下操作,而不会产生print
副作用.
Your main problem is that you did not initialize my_vector
before the for
loop. You could instead do the following and not get the print
side-effect.
my_vector <- vector("numeric", 10L)
for(i in 1:10) my_vector[i] <- i
my_vector
# [1] 1 2 3 4 5 6 7 8 9 10
但是请注意,这与使用sapply
进行以下操作相同,但是在这种情况下,您不需要声明,可以将结果分配给向量.
But note that this is just the same as doing the following with sapply
, but in this case you need no declaration and you can assign the result to a vector.
my_vector2 <- sapply(1:10, function(x) x)
my_vector2
# [1] 1 2 3 4 5 6 7 8 9 10
这篇关于将for循环的结果另存为r中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!