我想知道在R中构造动态大小数组的方法是什么.
举个例子,我想构造一个n向量,但它的维数n是动态确定的.以下代码将起作用:
> x=NULL
> n=2;
> for (i in 1:n) x[i]=i;
> x
[1] 1 2
Run Code Online (Sandbox Code Playgroud)
再举一个例子,我想构造一个by 2矩阵,其中行数n是动态确定的.但即使分配第一行我也失败了:
> tmp=c(1,2)
> x=NULL
> x[1,]=tmp
Error in x[1, ] = tmp : incorrect number of subscripts on matrix
> x[1,:]=tmp
Error: unexpected ':' in "x[1,:"
Run Code Online (Sandbox Code Playgroud)
感谢致敬!
填充数组后,可以对数组进行尺寸
标注(以一维,向量,方式)。模拟问题的一维代码段,这是使用较大尺寸标注的方法。
> x=c()
> tmp=c(1,2)
> n=6
> for (i in seq(1, by=2, length=n)) x[i:(i+1)] =tmp;
> dim(x) = c(2,n)
> x
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 1 1 1 1
[2,] 2 2 2 2 2 2
>
Run Code Online (Sandbox Code Playgroud)
如下所示(对于4 x 7数组示例) ,对于更通用的方法,i:(i+1)最好使用seq(i, length=2)或更佳的seq(i, length=length(tmp))方法,而不是使用它作为索引。
> x=c()
> tmp=c(1,2,3,4)
> n=7
> for (i in seq(1, by=length(tmp), length=n))
x[seq(i, length=length(tmp))] = tmp;
> dim(x) = c(length(tmp),n)
> x
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 1 1 1 1 1 1
[2,] 2 2 2 2 2 2 2
[3,] 3 3 3 3 3 3 3
[4,] 4 4 4 4 4 4 4
>
Run Code Online (Sandbox Code Playgroud)
我们还可以通过使用cbind / rbind重新分配x来获得类似的结果,如下所示。
> tmp=c(1,2)
> n=6
> x=rbind(tmp)
> for (i in 1:n) x=rbind(x, tmp);
> x
[,1] [,2]
tmp 1 2
tmp 1 2
tmp 1 2
tmp 1 2
tmp 1 2
tmp 1 2
tmp 1 2
Run Code Online (Sandbox Code Playgroud)
注意:可以摆脱“ tmp”名称(这些是rbind的副作用),
> dimnames(x)=NULL
我认为你要找的答案是rbind()和cbind():
> x=NULL # could also use x <- c()
> rbind(x, c(1,2))
[,1] [,2]
[1,] 1 2
> x <- rbind(x, c(1,2))
> x <- rbind(x, c(1,2)) # now extend row-wise
> x
[,1] [,2]
[1,] 1 2
[2,] 1 2
> x <- cbind(x, c(1,2)) # or column-wise
> x
[,1] [,2] [,3]
[1,] 1 2 1
[2,] 1 2 2
Run Code Online (Sandbox Code Playgroud)
尝试在尝试时动态分配"新索引"的策略可以在某些语言中完成,但不能在R中以这种方式完成.
您还可以使用Matrix包中提供的稀疏矩阵.它们将允许分配表单,M <- sparseMatrix(i=200, j=50, x=234)从而在第200行,第50列和其他任何地方产生单个值.
require(Matrix)
M <- sparseMatrix(i=200, j=50, x=234)
M[1,1]
# [1] 0
M[200, 50]
# [1] 234
Run Code Online (Sandbox Code Playgroud)
但我认为稀疏矩阵的使用最好保留在掌握常规矩阵后供以后使用.