Silver_80 -3 years ago 158
R Question

# apply and lapply in one function return an NAN

I have a function return list of list, I would like to find the standard deviation of the matrices of my output. The output of my function is a list of two list. I tried this code but it return me NAN. Since my function is complex, then I use this example from another question please see here since it is quite close to what I am trying to do.

``````> A <- matrix(c(1:9), 3, 3)
> A
[,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> B <- matrix(c(2:10), 3, 3)
> B
[,1] [,2] [,3]
[1,]    2    5    8
[2,]    3    6    9
[3,]    4    7   10
> my.list1 <- list(A, B)
``````

so the mean of the first list is:

``````  [,1] [,2] [,3]
[1,]  1.5  4.5  7.5
[2,]  2.5  5.5  8.5
[3,]  3.5  6.5  9.5
``````

Then the standard deviation will be:

``````          [,1]      [,2]      [,3]
[1,] 0.7071068 0.7071068 0.7071068
[2,] 0.7071068 0.7071068 0.7071068
[3,] 0.7071068 0.7071068 0.7071068

> c <- matrix(c(1:9), 3, 3)
> c
[,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

> d <- matrix(c(2:10), 3, 3)
> d
[,1] [,2] [,3]
[1,]    2    5    8
[2,]    3    6    9
[3,]    4    7   10

> my.list2 <- list(c, d)

my.list <-list(my.list1,my.list2)
``````

How can I get the standard deviation of my matrices on an element by element for the list?

You could bind your lists into an array, or perhaps make your function return an array(?), then you could use `apply()` to apply your chosen functions...

``````A <- matrix(1:9, 3, 3)
B <- matrix(2:10, 3, 3)
my.list1 <- list(A, B)

c <- matrix(1:9, 3, 3)
d <- matrix(2:10, 3, 3)
my.list2 <- list(c, d)
``````

Create array from all 4 lists

``````my.array1 <- abind::abind(c(my.list1, my.list2), along = 3)
``````

Find the `mean()` of the required dimension

``````apply(my.array1, c(1, 2), mean)
apply(my.array1, c(1,2), sd)
``````

Output

``````     [,1] [,2] [,3]
[1,]  1.5  4.5  7.5
[2,]  2.5  5.5  8.5
[3,]  3.5  6.5  9.5
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download