Space X
Space X

Reputation: 97

R how does a matrix gets distributed when using mcLapply

I have a matrix of 1000 rows and 16 columns. The first 8 columns represent one sample and remaining 8 columns represent another sample. For each of 1000 rows I need to calculate the ration of mean of first 8 columns and mean of last 8 columns. How can I perform this using mcLapply?

So far this is what I have:

library(parallel)

data <- a matrix of size 1000x16

mclapply(data, function(x){ 
                            mean(x[,1:8])/mean(x[,9:16])
                          }, mc.cores = detectCores())

I get the following error: error in x[, 1:8] : incorrect number of dimensions\n'

Thanks

Upvotes: 0

Views: 557

Answers (1)

mt1022
mt1022

Reputation: 17299

With lapply, the data matrix is treated as a vector and in each iteration, x is a single number from data. You can see this with the following example:

library(parallel)

x <- matrix(1:4, nrow = 2)
mclapply(x, print, mc.cores = 2)
# [[1]]
# [1] 1
# 
# [[2]]
# [1] 2
# 
# [[3]]
# [1] 3
# 
# [[4]]
# [1] 4

That's why you got incorrect dimension error. I guess what you wanted is:

rowMeans(data[,1:8])/rowMeans(data[,9:16])

If you have to use mclapply, you can loop over row numbers:

mclapply(1:nrow(data), function(x){ 
    mean(data[x,1:8])/mean(data[x,9:16])
}, mc.cores = detectCores())

Upvotes: 1

Related Questions