equivalent way using apply family instead of a for loop to get max value of each row in list of sublists R

StackOverflow https://stackoverflow.com/questions/18696589

  •  28-06-2022
  •  | 
  •  

Question

What would be the equivalent to this using apply family functions or a compbination between do.call and apply? I would like to keep it simple and when possible in one line:

a <- list(  as.data.frame(matrix(rnorm(12),4,3)),
            as.data.frame(matrix(rnorm(12),4,3)),
            as.data.frame(matrix(rnorm(12),4,3))
         )

l <- list()
for (i in 1:length(a)) {
  l[[i]] <- apply(a[[i]],1,max)
}

b <- do.call(data.frame, l)
Was it helpful?

Solution

I would use sapply for this particular example, however I don't know how representative this example is of your actual larger problem.

> sapply(a, function(x) apply(x, 1, max))
          [,1]      [,2]       [,3]
[1,] 0.5757814 0.9189774  0.6198257
[2,] 0.1836433 0.9438362  0.4179416
[3,] 1.5117812 1.1249309  1.3586796
[4,] 1.5952808 0.5939013 -0.1027877

sapply will simplify to a matrix whenever possible. If you want a data.frame, just wrap the output in data.frame.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top