R语言如何修复:incorrect number of subscripts on matrix
在编程中出现错误是很常见的,当我们的源代码变得越来越大时,其频率也会增加。在这篇文章中,我们将讨论如何解决:R语言中矩阵上的下标数不正确。
这个错误第一次出现时并没有给我们任何线索。这个错误可能是由于一个非常小的错误而发生的。这个错误对程序员来说可能很容易犯,但对大多数程序员来说,发现这个错误有时会成为挑战。
什么时候可能发生这种错误
当程序员试图在一个本身不是矩阵的数据结构上使用矩阵符号时,这些错误可能发生。这种类型的错误是正常的,但有时如果你不清楚所使用的数据结构,就很难发现它。
例子
# R program to illustrate when this
# error might occur
# Creating a vector
vect = rep(1, 5)
# Assign values in the created vector
for(i in 1:5)
{
# Assigning at all columns of the
# ith row
vect[i,] = 10
}
输出
为什么会出现这种错误
当程序员试图将矩阵符号应用于向量时,就会出现这种类型的错误。
例子
在下面的源代码中,我们创建了一个向量vect(1维的数据结构)。使用for-loop,我们从i = 1到i = 100进行迭代,在迭代的每一步,我们将数值10分配给第 i行的所有列。但是vect是一个一维的数据结构,我们在它上面应用矩阵符号。因此,下面的源代码会导致一个错误。”矩阵上的下标数目不正确”,在输出中可以清楚地看到。
# R program to illustrate reasons for the error
# Creating a vector
vect = rep(1, 5)
# Assign values in the created vector
for(i in 1:5)
{
# Assigning at all columns of the ith row
vect[i,] = 10
}
如何修复这个错误
修复这个错误是基于两种不同的意识形态,下面将讨论。
意识形态1: 当我们要处理一维数据结构的时候。
当我们确定要处理一维数据结构(如矢量)时,我们可以像下面的例子一样解决这个错误。
例子
# R program to fix the error
# Creating a vector
vect = rep(1, 5)
# Assign values in the created vector
# Note that we have removed the comma (,)
# Since we are dealing with 1-dimensional
# data structure
for(i in 1:5)
{
# Assigning 10 as the value
# at the ith index of the vect
vect[i] = 10
}
输出
意识形态2: 当我们要处理二维数据结构的时候。
当我们确定要处理二维数据结构(如矩阵)时,我们可以像下面的例子一样解决这个错误。
例子
# R program to fix the error
# Creating a 2-dimensional data structure (matrix)
# mat has 5 rows and 5 columns
mat = matrix(rep(0,5), nrow=5, ncol=5)
# Assign values in the created matrix
# Note that we have added the comma (,)
# Since we are dealing with 2-dimensional
# data structure
for(i in 1:5)
{
# Assigning 10 as the value
# at all columns of the ith row
mat[i,] = 10
}
# Print the matrix
print(mat)
输出