本文介绍了循环以在R中创建多个矩阵(可能使用粘贴)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建27个具有2列和可变行数的矩阵.我可以这样写27行代码:
I want to create 27 matrix with 2 columns and a variable number of rows.I could just write 27 lines of code, like this:
x1 = cbind(rep(1,34), rnorm(34))
x2 = cbind(rep(1,36), rnorm(36))
....
x27 = cbind(rep(1,k), rnorm(k))
但是它必须有更好的方法来做到这一点.我想到了一个循环,像这样:
But it must have a better way to do that. I thought of a loop, something like this:
aux = c(34, 36, ..., k) # auxiliar variable with number of rows for each matrix
for (i in 1:27) paste("x",i, sep="") = cbind(rep(1,aux[i]), rnorm(aux[i]))
但是,它不起作用.我觉得这是一个简单的任务,但是我没有主意.
However, it doesn't work. I feel like this is a simple task, but I am out of ideas.
有帮助吗?
ps .:我想到了一个数组,但无法使用它.我不知道,列表可以胜任这项工作.
ps.: I thought of an array, but I wasn't able to use it. Maybe a list can do the job, I don't know.
推荐答案
您需要assign
:
for (i in 1:27) {
assign(paste("x",i,sep=""), cbind(rep(1,aux[i]), rnorm(aux[i])))
}
这将在您的全局环境中创建27个矩阵对象.
This will create 27 matrix objects in your global environment.
这篇关于循环以在R中创建多个矩阵(可能使用粘贴)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!