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)))