Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用循环在R中创建矩阵_R_Loops_Matrix_Lars - Fatal编程技术网

使用循环在R中创建矩阵

使用循环在R中创建矩阵,r,loops,matrix,lars,R,Loops,Matrix,Lars,我试图在一个相对较小的数据集n=22,p=17上,在一个由LARS算法生成的线性回归上做一个遗漏交叉验证。基本上,我需要创建n个标准化数据矩阵,每个列由以平均值为中心的条目和以列的SD为标准的条目组成 我以前从未使用过列表,但只要不同矩阵的列可以被操作/标准化,我愿意创建列表 以下是我在R中尝试的: for (i in 1:n) { x.standardized.i <- matrix(data = NA, nrow = (n-1), ncol = p) #creates n mat

我试图在一个相对较小的数据集n=22,p=17上,在一个由LARS算法生成的线性回归上做一个遗漏交叉验证。基本上,我需要创建n个标准化数据矩阵,每个列由以平均值为中心的条目和以列的SD为标准的条目组成

我以前从未使用过列表,但只要不同矩阵的列可以被操作/标准化,我愿意创建列表

以下是我在R中尝试的:

for (i in 1:n)
{
  x.standardized.i <- matrix(data = NA, nrow = (n-1), ncol = p)  #creates n matrices, all n-1 x p
  for (j in 1:p)
  {
    x.standardized.i[,j] <- ((x[-i,j]-mean(x[-i,j]))/sd(x[-i,j])) #and standardizes the p variables with the ith row missing in each n matrix (i increments from 1 to n)
  }
}

我不确定是否可以共享数据,因为它与某个类的成绩相关,但当我运行代码时,它会通过循环并通过指定一个标准化矩阵停止,最后一行缺失为x.standarized.I

使用sapply和scale,您可以非常简单地做到这一点:

为确认各列以其平均值为中心,并通过一个标准差进行标准化:

apply(A, c(2, 3), mean)
apply(A, c(2, 3), sd)

您的循环返回一个矩阵,因为每次通过n个循环时,您都会在x.i中覆盖上一个循环的结果。你可以通过创建一个3D阵列来解决这个问题,并将其分配到三维空间,例如x.i.这太酷了,非常感谢!我想有一个更简单的方法。
A[,, 1] # all rows, all cols, first slice
A[,, 10] # all rows, all cols, tenth slice
apply(A, c(2, 3), mean)
apply(A, c(2, 3), sd)