Wady
Wady

Reputation: 65

Errors while using cbind with a matrix

I have a list of 40 data sets who all have the same columns. I want to bind the 7th column of each data set. I thought about doing this with a matrix using cbind. This is my code:

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)

I get these warnings :

Warning messages: 1: In replace(q[, i], 1:766, x[, 9]) : the number of objects to be replaced is not a multiple of the size of the replacement !

Upvotes: 0

Views: 164

Answers (1)

Vincent Guillemot
Vincent Guillemot

Reputation: 3429

Let's take a smaller example: cbind the 5th columns of each of these 3 matrices

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

First we put the 3 matrices in a list

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

Then we could use, as in your question, a for loop

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

Or we could use some magical R functions to get the result in one slightly more obscure command

res2 <- do.call(cbind, lapply(M, "[",,5))

Upvotes: 1

Related Questions