r - 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.
解决方案
你需要更多类似的东西:
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)
推荐阅读
- ios - 如何从实时数据库 Firebase 观察更多级别?
- python-3.x - 我想从列表中选择我的 id 符合条件的表
- javascript - 如何在何时获取值是空的
- web-applications - 调试运行 Tizen Web 应用程序...?
- swift - 在特定时间重复本地通知,并在同一时间间隔后重复
- reactjs - 如何模拟 i18n.addResourceBundle?
- scala - 通过时间戳scala更新数据帧值
- php - 如何在 PHP 中使用多个搜索条件查找相关库存?
- regex - 使用 BASH 和正则表达式按名称提取函数体
- python - 在 Windows 中将字符串传递给 pathlib.Path 时出现操作系统错误