11

如何在 R 中减去两个结构相同的列表。以下函数创建数据集

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

我想从 dataSet2 中减去 dataSet1

4

1 回答 1

18

这取决于结构。在这种情况下mapply应该工作:

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

编辑:另一个解决方案Map()

Map('-', dataSet2, dataSet1)
于 2012-11-28T13:45:16.260 回答