Search code examples
rarrayssumapply

Sum a number to each element of an array


I would like to sum 5 to each element of an array (not through all dimensions) without using a loop for. As the result, I want to get an array with the exact same dimensions, but each element should have 5 added to it. I tried using the sum and the apply functions, but I either get the sum of each of the elements (one number), or this error message:

Error in apply(b[, , , 2], 5, FUN = sum, na.rm = T) : 
  'MARGIN' does not match dim(X)

I need to have na.rm = T, because there are a lot of NA in my dataset, so I want to get NA + 5 = 5

Here is an example where I'm trying to sum 5 to all dimensions but to [,,,1] :

b <- array(seq(1,48,1), dim = c(4,2,3,2))
b[4,2,3,2] <- NA

I tried:


sum(b[,,,2], 5, na.rm = T)

I was expecting to get as an answer:

(a <- array(c(seq(1,24,1),seq(25,47,1)+5, 5), dim = c(4,2,3,2)))


Solution

  • R by default supports adding to matricies and arrays. You can just use the + operator to add a value to each element of a vector/matrix/array. Since you only want to affect parts of that array, just use square brackets to subset the parts you want to affect:

    b[,,,2] <- b[,,,2] + 5
    
    table(b==a, useNA='always')
    
    TRUE <NA> 
      47    1 
    

    You have NA values in your array. In R, by default, operations involving an NA return NA. So in this case, the NA values in b will remain NA after the addition.

    If you want different behavior, for example if you want NA + 5 = 5, then you need to convert the NA values to 0 in the parts of the array you care about before doing the addition

    To replace all NAs with 0:

    b[is.na(b)] <- 0
    

    To only do that in b[,,,2]:

    b[,,,2][is.na(b[,,,2])] <- 0