3

I'm sorry but I can't find a way to replace every 0 in a 3-dimension array by the mean of the column they are in.

Thanks. So, for example, let's say I have this array j

j
, , 1

      [,1] [,2]
[1,]    0    6
[2,]    1    5
[3,]    2    2

, , 2

      [,1] [,2]
[1,]   11    0
[2,]   14   12
[3,]    0   14

, , 3

     [,1] [,2]
[1,]   19   22
[2,]   20   23
[3,]   21   24

I would like

j
, , 1

      [,1] [,2]
[1,]    1    6
[2,]    1    5
[3,]    2    2

, , 2

      [,1] [,2]
[1,]   11    26/3
[2,]   14   12
[3,]   25/3   14

, , 3

     [,1] [,2]
[1,]   19   22
[2,]   20   23
[3,]   21   24
user1627466
  • 411
  • 5
  • 14
  • 1
    Please make your situation reproducible, i.e. provide us with the data and the code needed to mimic your situation. See http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example for more tips on how to do this. – Paul Hiemstra Mar 21 '13 at 14:04

1 Answers1

3

You can use apply for this.

Starting with the following data :

arr <- array(0:5,dim=c(4,3,2))

, , 1

     [,1] [,2] [,3]
[1,]    0    4    2
[2,]    1    5    3
[3,]    2    0    4
[4,]    3    1    5

, , 2

     [,1] [,2] [,3]
[1,]    0    4    2
[2,]    1    5    3
[3,]    2    0    4
[4,]    3    1    5

You can do :

apply(arr, c(2,3),function(v) { v[v==0] <- mean(v); v})

Which gives :

, , 1

     [,1] [,2] [,3]
[1,]  1.5  4.0    2
[2,]  1.0  5.0    3
[3,]  2.0  2.5    4
[4,]  3.0  1.0    5

, , 2

     [,1] [,2] [,3]
[1,]  1.5  4.0    2
[2,]  1.0  5.0    3
[3,]  2.0  2.5    4
[4,]  3.0  1.0    5
juba
  • 47,631
  • 14
  • 113
  • 118