使用R中的(嵌套)循环构造向量 [英] Constructing vectors using (nested)loops in R
问题描述
我已经在互联网上扫描了很多论坛,但是找不到解决我问题的明确答案,因此我决定将其发布在这里.我正在使用的程序是R.
I've scanned quite some fora on the internet but couldn't find a clear answer to my problem, hence I decided to post it here. The program I am using is R.
以下问题是我似乎找不到解决方案的地方.我的任务是使用嵌套循环(因此没有rep())构造向量(1,2,2,3,3,3 ...,10,...,10).到目前为止,我设法构造了所有元素的列表,但无法将其转换为所需的向量.我尝试了很多方法,例如将数据转换为矩阵并进行转置等.
The following problem is where I can't seem to find a solution. I am tasked with constructing a vector (1,2,2,3,3,3...,10,...,10) using a nested loop (so no rep()). So far I managed to construct a list of all elements but can't manage to convert it into the desired vector. I have tried quite some methods, like converting the data into a matrix and transposing it etc.
到目前为止,还没有一种方法可行,也许对此事有更深入了解的人可以帮助我.
So far not a single method has worked, perhaps someone with more insight on this matter could help me.
这是我到目前为止所得到的:
This is what I've got so far:
for (i in 1:10){
for (j in 1:10)
if (j<=i)
{
x = c(i)
print(x)
}
}
为我提供了:
[1] 1
[1] 2
[1] 2
[1] 3
[1] 3
[1] 3
[1] 4
[1] 4
[1] 4
[1] 4
[1] 5
[1] 5
[1] 5
[1] 5
[1] 5
[1] 6
[1] 6
[1] 6
[1] 6
[1] 6
[1] 6
[1] 7
[1] 7
[1] 7
[1] 7
[1] 7
[1] 7
[1] 7
[1] 8
[1] 8
[1] 8
[1] 8
[1] 8
[1] 8
[1] 8
[1] 8
[1] 9
[1] 9
[1] 9
[1] 9
[1] 9
[1] 9
[1] 9
[1] 9
[1] 9
[1] 10
[1] 10
[1] 10
[1] 10
[1] 10
[1] 10
[1] 10
[1] 10
[1] 10
[1] 10
提前谢谢!
推荐答案
如果剩下的问题是将结果存储在矢量中而不是打印出来,则可以这样进行:
If storing the result in a vector, instead of printing it, is the remaining problem, this can be done this way:
result <- vector(mode = "integer")
k <- 1
for (i in 1:10){
for (j in 1:10)
if (j<=i)
{
result[k] = c(i)
k <- k+1
}
}
head(result)
这篇关于使用R中的(嵌套)循环构造向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!