4
votes

I have a matrix of lists.

How do I apply a function to each set of the lists and return a matrix of the same dimensions as my original matrix?

I tried apply(X=data.matrix , MARGIN=c(1,2) , function(x) min(x$P) ) but it returned Error in min(x$P) : (converted from warning) no non-missing arguments to min; returning Inf

EDIT: An example of the type of data I have:

data.matrix = list()

data.matrix$first = list()
data.matrix$second = list()
data.matrix$third = list()

data.matrix$first$a = data.frame(P=runif(3))
data.matrix$first$b = data.frame(P=runif(3))
data.matrix$first$c = data.frame(P=runif(3))

data.matrix$second$a = data.frame(P=runif(3))
data.matrix$second$b = data.frame(P=runif(3))
data.matrix$second$c = data.frame(P=runif(3))

data.matrix$third$a = data.frame(P=runif(3))
data.matrix$third$b = data.frame(P=runif(3))
data.matrix$third$c = data.frame(P=runif(3))

data.matrix = do.call(rbind,data.matrix)

I want to get the min (or whatever else) on each element of the matrix.

Thanks!

1
Reproducible example, please!Metrics
Example produced - thanks for the reminder :)James
Try sapply(data.matrix, function(x) min(x$P)) If you need to fill the min values to replace the data.frame lapply(data.matrix, function(x) {x$P <- min(x$P);x})akrun
Technically, you have a two-dimensional list of data framesMarat Talipov
Akrun, thanks, that worked! I was trying apply because it is a matrix and getting no where.James

1 Answers

3
votes

You can try

sapply(data.matrix, function(x) min(x$P))

If the min values should replace the P column

lapply(data.matrix, function(x) {x$P <- min(x$P);x})