如何使用for循环制作向量 [英] How to make a vector using a for loop

查看:328
本文介绍了如何使用for循环制作向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对R(以及一般的编程)非常陌生,并且我已经坚持了几天这个(可能非常简单)的问题...

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

如何使用 for 循环来生成向量 3 6 12 24 48 96 192 384 768

How would one make the vector 3 6 12 24 48 96 192 384 768 with a for loop?

到目前为止,我设法提出的是:

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!

推荐答案

好的,你需要知道的第一件事是如何将东西附加到矢量。你想要的功能就足够了追加

Okay, the first thing you need to know is how to append things to a vector. Easily enough the function you want is append:

x <- c(1, 2)
x <- append(x, 3)

将使向量x包含(1,2,3)就像你已经完成 x< - (1,2,3)。接下来你需要意识到的是,目标向量的每个成员都是前一个成员的两倍,这在for循环中很容易实现

will make the vector x contain (1, 2, 3) just as if you'd done 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

n <- 1
for (i in 1:8)
{
    n <- n*2
}

将使每个循环加倍。显然,您可以通过在 n< - n * 2 语句之前或之后放置其他语句,将其用于加倍或未加倍的形式。

will have n double up each loop. 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.

希望你可以将这两个东西放在一起,形成你想要的循环。

Hopefully you can put these two things together to make the loop you want.

这篇关于如何使用for循环制作向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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