理解R中的简单for循环(Understanding simple for loop in R)

编程入门 行业动态 更新时间:2024-10-26 04:30:28
理解R中的简单for循环(Understanding simple for loop in R)

为什么以下代码会产生

x=10:14 for (i in x) { print(x) }

这个输出

[1] 10 11 12 13 14 [1] 10 11 12 13 14 [1] 10 11 12 13 14 [1] 10 11 12 13 14 [1] 10 11 12 13 14

我认为for循环会执行5次。 这是因为x=10,x=11,x=12,x=13,x=14并且每次都打印x使得它仅给出输出10 11 12 13 14 。

为什么循环25次?

我是R的新手。所以有人可以告诉我这里发生了什么

Why does the following code produces

x=10:14 for (i in x) { print(x) }

this output

[1] 10 11 12 13 14 [1] 10 11 12 13 14 [1] 10 11 12 13 14 [1] 10 11 12 13 14 [1] 10 11 12 13 14

I thought the for loop would execute 5 times. That is for x=10,x=11,x=12,x=13,x=14 and at each time print x so that it would just give the output 10 11 12 13 14.

Why does it loop 25 times?

I am completely new to R. So can someone please tell me what is happening here

最满意答案

您首先定义了一个序列x <- 10:14 。 由于你是R的初学者,值得指出的是,使用=作为赋值通常被认为是不好的做法,尽管R容忍这种“方言”,这种方言通常由没有经验的R程序员使用,具有其他编程语言的背景。

无论如何,在这种情况下你的循环变量是i 。 循环运行五次,因为i的值遍历由x定义的范围,即10,11,12,13,14。

但是,在循环中,您永远不会使用i的值。 例如,您可以简单地使用print(i) ,如上面的注释所示,并查看值如何从10更改为14.相反,您每次都打印x的值,这是在循环外定义的向量这永远不会改变。 该向量x包含五个元素10,11,12,13,14,每次调用函数print(x)都会显示这些元素。 由于x包含五个数字,因此输出中总共可以获得25个打印数字。

总之,你的循环打印包含五个元素的相同向量的五倍。 希望这可以帮助。

You have first defined a sequence x <- 10:14. Since you are a beginner in R, it is worth pointing out that it is generally considered as bad practice to use = for assignments, although R tolerates such 'dialect' that is typically used by inexperienced R programmers with a background in other programming languages.

Anyway, your looping variable in this case is i. The loop runs five times, as the value of i traverses the range defined by x, which is 10, 11, 12, 13, 14.

In your loop, however, you never use the value of i. For instance, you could simply use print(i), as suggested in a comment above, and see how the value changes from 10 to 14. Instead, you are printing each time the value of x, which is a vector defined outside the loop and that is never changed. This vector x contains five elements 10, 11, 12, 13, 14, which are displayed each time the function print(x) is called. Since x contains five numbers, you obtain a total of 25 printed numbers in your output.

In conclusion, your loop prints five times the same vector containing five elements. Hope this helps.

更多推荐

本文发布于:2023-07-26 19:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279595.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简单   Understanding   loop   simple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!