组装数组而不在R中循环

时间:2017-07-31 23:28:35

标签: arrays r for-loop

假设有两个矩阵AB

(A <- mdat <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12), nrow = 4, ncol = 3))
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

(B <- mdat <- matrix(rev(c(1,2,3,4,5,6,7,8,9,10,11,12)), nrow = 4, ncol = 3))
     [,1] [,2] [,3]
[1,]   12    8    4
[2,]   11    7    3
[3,]   10    6    2
[4,]    9    5    1

我想创建如下定义的数组C

C <- array(0, dim=c(4,3,3))
for(i in 1:ncol(A))
for(j in 1:ncol(B))
   C[, i, j] = A[,i] + B[,j]

如果没有循环,怎么能很好地完成呢?

3 个答案:

答案 0 :(得分:4)

重复每个矩阵的列,然后添加并重置尺寸:

out <- A[,rep(1:ncol(A),3)] + B[,rep(1:ncol(B),each=3)]
dim(out) <- c(4,3,3)

identical(out,C)
#[1] TRUE

答案 1 :(得分:3)

您可以使用apply方法构建具有所需维度属性的数组(从您的注释中切换A和B的位置):

array(apply(B, 2, "+", A), c(4,3,3))

, , 1

     [,1] [,2] [,3]
[1,]   13   17   21
[2,]   13   17   21
[3,]   13   17   21
[4,]   13   17   21

, , 2

     [,1] [,2] [,3]
[1,]    9   13   17
[2,]    9   13   17
[3,]    9   13   17
[4,]    9   13   17

, , 3

     [,1] [,2] [,3]
[1,]    5    9   13
[2,]    5    9   13
[3,]    5    9   13
[4,]    5    9   13

答案 2 :(得分:1)

那会有用吗?

    func alertForPurchaseResult(result : PurchaseResult) -> UIAlertController {
        switch result {
        case .success(let product):
            return alertWithTitle(title: "Thank You", message: "Purchase completed")
        case .error(let error):
            switch error.code {
            case .unknown: return alertWithTitle(title: "Purchase Error", message: "Unknown error. Please contact support")
            case .clientInvalid: return alertWithTitle(title: "Purchase Error", message: "Not allowed to make the payment")
            case .paymentCancelled: return alertWithTitle(title: "Payment Cancelled", message: "Payment Cancelled")
            case .paymentInvalid: return alertWithTitle(title: "Purchase Error", message: "The purchase identifier was invalid")
            case .paymentNotAllowed: return alertWithTitle(title: "Purchase Error", message: "The device is not allowed to make the payment")
            case .storeProductNotAvailable: return alertWithTitle(title: "Purchase Error", message: "The product is not available in the current storefront")
            case .cloudServicePermissionDenied: return alertWithTitle(title: "Purchase Error", message: "Access to cloud service information is not allowed")
            case .cloudServiceNetworkConnectionFailed: return alertWithTitle(title: "Purchase Error", message: "Could not connect to the network")
            default: return alertWithTitle(title: "Purchase Error", message: "Unknown error")
            }
        }  
    }