[英]How to make a vector using a for loop
I'm very new to R (and programming in general) and I've been stuck on this (probably very easy) question for a few days...我对 R(以及一般的编程)非常陌生,几天来我一直被困在这个(可能很简单)的问题上......
How would one make the vector 3 6 12 24 48 96 192 384 768
with a for
loop?如何使用for
循环制作向量3 6 12 24 48 96 192 384 768
?
All I've managed to come up with so far is something along the lines of:到目前为止,我设法想出的只是以下内容:
x=numeric()
for (i in 1:8) (x=2*i[-1])
However, that doesn't work.但是,这不起作用。 I think one of the main problems is that I don't understand how to index numbers in a sequence.我认为主要问题之一是我不明白如何在序列中索引数字。
If anyone could point me in the right direction that would be such a great help!如果有人能指出我正确的方向,那将是非常有帮助的!
x=c()
x[1] = 3
for (i in 2:9) {
x[i]=2*x[i-1]
}
Okay, the first thing you need to know is how to append things to a vector.好的,您需要知道的第一件事是如何将事物附加到向量中。 Easily enough the function you want is append
:很容易,你想要的功能是append
:
x <- c(1, 2)
x <- append(x, 3)
will make the vector x contain (1, 2, 3)
just as if you'd done x <- (1, 2, 3)
.将使向量 x 包含(1, 2, 3)
就像你已经完成x <- (1, 2, 3)
。 The next thing you need to realise is that each member of your target vector is double the one before, this is easy to do in a for loop您需要意识到的下一件事是目标向量的每个成员都是之前的两倍,这在 for 循环中很容易做到
n <- 1
for (i in 1:8)
{
n <- n*2
}
will have n double up each loop.每个循环将有 n 倍。 Obviously you can use it in its doubled, or not-yet-doubled form by placing your other statements before or after the n <- n*2
statement.显然,您可以通过将其他语句放在n <- n*2
语句之前或之后,以加倍或尚未加倍的形式使用它。
Hopefully you can put these two things together to make the loop you want.希望您可以将这两件事放在一起来制作您想要的循环。
Really, folks.真的,伙计们。 Stick with the solution hiding in Arun's comment.坚持隐藏在 Arun 评论中的解决方案。
Rgames> 3*2^(0:20)
[1] 3 6 12 24 48 96 192 384 768
[10] 1536 3072 6144 12288 24576 49152 98304 196608 393216
[19] 786432 1572864 3145728
sapply(1:9, function(i) 3*2**(i-1) )
You could, if you know python use the package reticulate to do it which would be much easier than in r (which is how I did a similar task).你可以,如果你知道 python 使用包 reticulate 来做到这一点,这比在 r 中容易得多(这是我完成类似任务的方式)。
If you don't have the package then do:如果您没有该软件包,请执行以下操作:
install.packages('reticulate')
Then if you do, you could do那么如果你这样做,你可以做
library('reticulate')
py_run_string('vector = [n*2 for n in range(1, 9, 1)']
#Then you can call the vector by:
print(py$vector)
#And do whatever you want with it.
I know that this was more python than r and it was made a bit more complicated then it could have been but for me personally, I found python more easier than r for manipulating vectors (or lists, the python equivalent).我知道这比 r 更像是 python,而且它比 r 更复杂,但对我个人而言,我发现 python 比 r 更容易操作向量(或列表,python 等价物)。 I hope that this answers your question.我希望这能回答你的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.