R 向矩阵中添加列

R 向矩阵中添加列,r,R,这里怎么了 datMat <- matrix(runif(40,1,20),ncol=4) datMat[,5]=rep(1,nrow(datMat)) 输出: Error in `[<-`(`*tmp*`, , 5, value = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)) : subscript out of bounds 为什么我不能添加新列?您正在尝试引用矩阵中尚不存在的列。可以通过以下方式向矩阵中添加列: datMat=cbinddatMa

这里怎么了

datMat <- matrix(runif(40,1,20),ncol=4)
datMat[,5]=rep(1,nrow(datMat))
输出:

Error in `[<-`(`*tmp*`, , 5, value = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)) : 
  subscript out of bounds

为什么我不能添加新列?

您正在尝试引用矩阵中尚不存在的列。可以通过以下方式向矩阵中添加列:

datMat=cbinddatMat,rep1,nrowdatMat 但这是低效的。最好创建一个完全使用0或NA的矩阵,然后添加条目,如: datMat=matrixcrunif40,1,20,repNA,10,ncol=5,byrow=F datMat[,5]=rep1,nrowdatMat

cbinddatMat,1如错误所述,为什么对于矩阵,您需要分配给现有索引。矩阵不是数据帧。structurecdatMat,rep1,nrowdatMat,.Dim=cnrowdatMat,ncoldatMat+1