Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting two identically structured lists in R

Tags:

r

How do I subtract two identically structured lists in R. The following function creates the data sets

dataSet <- function(x,y){
    data <- lapply(1:4, function(x)
           do.call(cbind,do.call(cbind,
                                 lapply(lapply(1:5,function(y)
                                               cbind(rnorm(10))), data.frame)) ))
    pVariatesNames <- paste("s",seq(from=380, length.out=5),sep="")
    nCasesNames <- c("Paper","R","G","B")
    customerNames <- paste("Customer",seq(from=1, length.out=10),sep=" ")
    names(data) <- nCasesNames
    for(i in 1:4) {
        colnames(data[[i]]) <- pVariatesNames
        rownames(data[[i]]) <- customerNames
    }
    return(data)
}
dataSet1 <- dataSet(4,5); dataSet1
dataSet2 <- dataSet(4,5); dataSet2

I would like to subtract dataSet1 from dataSet2

like image 252
Ragy Isaac Avatar asked Nov 28 '12 13:11

Ragy Isaac


1 Answers

It depends on the structure. In this case mapply should work:

mapply('-', dataSet2, dataSet1, SIMPLIFY = FALSE)

Edit: another solution with Map()

Map('-', dataSet2, dataSet1)
like image 68
Sacha Epskamp Avatar answered Sep 22 '22 15:09

Sacha Epskamp