Context: I'm working with survey data organized as a 4D array with this structure: m[n_sites, n_surveys, n_years, n_species].
Question: There are data missing randomly, though, and I want to move the missing data to the end of each row.
Example: Here's the original data:
, , 1, 1
1 2 3 4 5
1 NA 2 NA 2 3
2 NA 3 1 NA NA
3 4 NA NA 4 6
4 2 NA NA 2 1
... and I want to rearrange this to be:
, , 1, 1
1 2 3 4 5
1 2 2 3 NA NA
2 3 1 NA NA NA
3 4 4 6 NA NA
4 2 2 1 NA NA
Note: The data are very large, though, so I need something efficient and fairly simple.
Reproducible code:
library(magrittr) ## for %>% pipe
library(reshape2) ## for acast
set.seed(1)
# Simulate survey data
df <- expand.grid(
species = c(1,2),
year = c(1,2,3),
site = c(1,2,3,4),
survey = c(1,2,3,4,5))
df$counts <- rpois(n = nrow(df), lambda = 3)
# Add random NAs (missing data)
posNA <- sample(x = 1:nrow(df), size = 0.5 * nrow(df), replace = FALSE)
df$counts[posNA] <- NA
# Cast to 4d array
m <- df %>% acast(site ~ survey ~ year ~ species)