首页 > 解决方案 > How can I append a result in a vector without overwriting? (loop)

问题描述

I am new to R and I am trying to program Pascal's triangle in Rstudio. I want to create a 11X11 matrix with the results. Here's my code:

M<-c()
for (n in 0:10) {
  for (k in 0:10) {

    result <- choose(n,k)
    list_results <- append(result,M)
  }
}

Pascal <- matrix(list_results, ncol=11)

The code creates a 11x11 matrix full of ones because the loop is only saving the last result (1) and overwritting the previous ones that calculates. How can I solve this? I don't know what is the correct command to use to add the result to the vector that I created in the first line: append, rbind, or paste?

Thank you.

标签: rloops

解决方案


你需要更多类似的东西:

Pascal <- matrix(nrow=11, ncol=11)
for (n in 0:10) {
  for (k in 0:10) {

    result <- choose(n,k)
    Pascal[(k+1), (n+1)] <- result
  }
}

或者,按照您原来的策略,您可以这样做:

M<- NULL
for (n in 0:10) {
  for (k in 0:10) {

    result <- choose(n,k)
    M <- c(M, result)
  }
}

Pascal <- matrix(M, ncol=11)

推荐阅读