0
votes

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 !

1
What is ListeActions ? your example is not reproductible. Can you provide one? And you get the warning because you try to replace q[,i] with cbind(q[,i], x[,9]) which is 2 elements. What you want to do is bind the 7th or 9th column? (not the same info in your question)cderv
and q is defined inside your function. You should get it out if you want to consider it as argument.cderv

1 Answers

1
votes

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))