使用带有矩阵的cbind时出错

时间:2016-03-29 13:30:29

标签: r cbind

我有40个数据集的列表,这些数据集都具有相同的列。我想绑定每个数据集的第7列。我想过使用cbind用矩阵做这个。这是我的代码:

RetRates <- function(q) {
    q <- matrix(nrow = 766, ncol = length(ListeActions),
                data = rep(0, 766), byrow = TRUE)
    s <- 0
    for (i in 1:length(ListeActions)) {
        x <- ListeActions[[i]]
        q[,i] <- cbind(q[,i], x[,9])  ## I need the 9th column
    }
    return(q)
}

Hedi <- matrix(nrow = 766, ncol = length(ListeActions),
               data = rep(0, 766), byrow = TRUE)
Hedi <- RetRates(Hedi)

我收到了这些警告:

  

警告信息:1:替换(q [,i],1:766,x [,9]):数字   要替换的对象不是大小的倍数   更换!

1 个答案:

答案 0 :(得分:1)

我们举一个较小的例子:cbind这3个矩阵中每个矩阵的第5列

d1 <- matrix(runif(30), 5, 6)
d2 <- matrix(rnorm(30), 5, 6)
d3 <- matrix(rnorm(30), 5, 6)

首先我们将3个矩阵放在一个列表中

M <- list(d1=d1, d2=d2, d3=d3)

然后我们可以像你的问题一样使用for循环

res1 <- matrix(NA, nrow=5, ncol=length(M))
for (i in 1:length(M)) {
  res1[, i] <- M[[i]][,5]
}

或者我们可以使用一些神奇的R函数将结果放在一个稍微模糊的命令

res2 <- do.call(cbind, lapply(M, "[",,5))
相关问题