应用后停止3D阵列展平

时间:2017-05-25 23:41:49

标签: arrays r apply

我在3D数组上运行应用程序,它正在返回一个2D数组

m = replace(array(1:16,dim=c(4,2,2)), c(1,13,14), NA)
dim(m)
# [1] 4 2 2

对于每个切片,我想用平均值(对于那个切片)替换该切片的NA,对于上面的矩阵,在第一维中有4个条目,这里有以下意思:

apply(m,1,function(x) mean(x,na.rm = T))
# [1]  7  6  9 10

这是我想用来替换的功能:

replace_na_with_mean = function(a){ 
  a[is.na(a)] = mean(a, na.rm = T); 
  #print(dim(a)); 
  return(a)
}

这是理想的结果:

# out[1,,] should have 7s instead of it's NAs
# out[2,,] should have 6s instead of it's NAs
# out[3,,] should have 9s instead of it's NAs
# out[4,,] should have 10s instead of it's NAs

这有效:

out = m
for(i in 1:dim(m)[1]){
  out[i, , ] = replace_na_with_mean(m[i, , ])
}
# here is the working output:
# > m[1,,]
# [,1] [,2]
# [1,]   NA    9
# [2,]    5   NA
# > out[1,,]
# [,1] [,2]
# [1,]    7    9
# [2,]    5    7

但我无法通过申请完成。

out = m
out[] = apply(m,1,replace_na_with_mean)
# this is the failing output:
# > m[1,,]
# [,1] [,2]
# [1,]   NA    9
# [2,]    5   NA
# > out[1,,]
# [,1] [,2]
# [1,]    7    3
# [2,]    2    4

0 个答案:

没有答案