简体   繁体   English

我正在尝试在 R 中创建一个带有 while 循环的 Collat​​z 序列。我在这个 while 循环中做错了什么?

[英]I am trying to create a Collatz sequence with while loop in R. What am i doing wrong in this while loop here?

I am trying to create a Collatz sequence with while loop in R.我正在尝试在 R 中创建一个带有 while 循环的 Collat​​z 序列。

vector <-  NULL
n <- 10
while (n != 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- (n * 3) + 1
  }
  vector <- c(vector, cbind(n))
  print(vector)
}

After running the code, I got:运行代码后,我得到:

[1] 5
[1]  5 16
[1]  5 16  8
[1]  5 16  8  4
[1]  5 16  8  4  2
[1]  5 16  8  4  2  1

How do I do it such that it only shows the last row?我该怎么做才能只显示最后一行? What went wrong in my code?我的代码出了什么问题? Thanks for any help on this.感谢您对此的任何帮助。

You have several ways to deal with print(vector)你有几种方法来处理print(vector)

  • add if condition before print(vector) , ie,print(vector)之前添加if条件,即
vector <-  NULL
n <- 10
while (n != 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- (n * 3) + 1
  }
  vector <- c(vector, cbind(n))
  if (n==1)  print(vector)
}
  • move it outside while loop, ie,将它移到while循环之外,即
vector <-  NULL
n <- 10
while (n != 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- (n * 3) + 1
  }
  vector <- c(vector, cbind(n))
}
print(vector)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R中的快速傅立叶变换。我在做什么错? - Fast Fourier Transform in R. What am I doing wrong? 我正在尝试使用 R 获取矩阵中列的乘积。 我究竟做错了什么? - I'm trying to take the product of the columns in a matrix using R. What am I doing wrong? 我是 r 的新手。我试图通过使用 for 循环使我的代码不那么复杂 - I am new to r. I am trying to make my code less complicated by using a for loop 我正在尝试编写类似于for循环的while循环,我该如何在R中进行呢? - I am trying to write a while loop similar to my for loop.How should I go about it in R? R:我在这个带有 if-else 语句的 for 循环中做错了什么? - R: What am I doing wrong in this for-loop with an if-else statement? 绘制覆盖,所以在 R 循环结束时,所有元素都从列表的最后一个元素中提取出来。 我究竟做错了什么? - Plots overwriting, so at the end of the R loop all have pulled from last element of list. What am I doing wrong? 为了加载或安装程序包而无法进行循环。 我究竟做错了什么? - Loop in order to load or install packages does not work. What am I doing wrong? 我在做什么错(data.table,R)? - What am I doing wrong (data.table, R)? dplyr (R) 中的 stderr:我做错了什么? - stderr in dplyr (R): What am I doing wrong? 我在 R 到 python 的翻译中做错了什么? - What I am doing wrong in R to python translation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM