R cbind(1,<;数值>;)和cbind(1,<;矩阵>;)是否有一致的方法?

R cbind(1,<;数值>;)和cbind(1,<;矩阵>;)是否有一致的方法?,r,R,我正在使用一些代码,这些代码与以下简单脚本有着重要的相似之处: scores <- matrix(rnorm(4*20), ncol=4,nrow=20) result <- matrix(NA, ncol=2, nrow=20) index <- as.logical(rbinom(20,1,.2)) result[index, 1:3] <- cbind(1, scores[index,3:4]) 其中和(索引)=0: > scores <- matri

我正在使用一些代码,这些代码与以下简单脚本有着重要的相似之处:

scores <- matrix(rnorm(4*20), ncol=4,nrow=20)
result <- matrix(NA, ncol=2, nrow=20)
index <- as.logical(rbinom(20,1,.2))
result[index, 1:3] <- cbind(1, scores[index,3:4])
其中
和(索引)=0

> scores <- matrix(rnorm(4*20), ncol=4,nrow=20)
> result <- matrix(NA, ncol=3, nrow=20)
> index <- rep(FALSE, 20)
> result[index, 1:3] <- cbind(1, scores[index,3:4])
Warning message:
In cbind(1, scores[index, 3:4]) :
  number of rows of result is not a multiple of vector length (arg 1)
> #cbinding to a zero-row matrix returns an error
>评分结果索引结果[索引,1:3]#C绑定到零行矩阵会返回错误
这个问题的明显解决方案如下:

scores <- matrix(rnorm(4*20), ncol=4,nrow=20)
result <- matrix(NA, ncol=3, nrow=20)
index <- as.logical(rbinom(20,1,.1))
if(sum(index) > 1){
    result[index, 1:3] <- cbind(1, scores[index,3:4])
}else{
    if(sum(index) ==1){
        result[index, 1:3] <- c(1, scores[index,3:4])
    }
}

scores一般来说,将
drop=FALSE
添加到
mtx[1,]
调用可以避免单行提取和采用矩阵结构的后续操作出现的困难:

result[index, 1:2] <- cbind(1, scores[1, 3:4, drop=FALSE])  # no error
# Also adding a third column to avoid dimension mismatch
scores <- matrix(rnorm(4*20), ncol=4,nrow=20)
result <- matrix(NA, ncol=3, nrow=20)
index <- as.logical(rbinom(20,1,.2))
result[index, 1:3] <- cbind(1, scores[index,3:4, drop=FALSE])

result[index,1:2]另外,一般来说,如果应用程序对性能敏感,那么cbind会让你大失所望。好的一点——这是在批处理的环境中,所以我相信cbind会减慢速度。如果我编写了原始代码,我会在
data.table
中完成所有工作,但由于我只是修复和扩展其他人的代码,从头开始需要做很多工作……事实上,将零行对象分配给零行对象不会产生错误——它不会像您预期的那样产生任何效果。(尝试
索引
result[index, 1:2] <- cbind(1, scores[1, 3:4, drop=FALSE])  # no error
# Also adding a third column to avoid dimension mismatch
scores <- matrix(rnorm(4*20), ncol=4,nrow=20)
result <- matrix(NA, ncol=3, nrow=20)
index <- as.logical(rbinom(20,1,.2))
result[index, 1:3] <- cbind(1, scores[index,3:4, drop=FALSE])