Rel_Ai
Rel_Ai

Reputation: 591

Finding minimum of each rows from a list and their corresponding column number

A reproducible example:

mat1 <- matrix(c(1,2,4,2,4,2,4,6,5,7,8,3), nrow = 3, ncol = 4, byrow = T)
mat2 <- matrix(c(2,1,7,8,2,6), nrow = 3, ncol = 2, byrow = T)
mat3 <- matrix(c(3,2,3,5,7,5,4,5,6,4,2,3,4,5,2), nrow = 3, ncol = 5, byrow = T)

list.mat <- list(mat1,mat2,mat3)

> list.mat

[[1]]
     [,1] [,2] [,3] [,4]
[1,]    1    2    4    2
[2,]    4    2    4    6
[3,]    5    7    8    3

[[2]]
     [,1] [,2]
[1,]    2    1
[2,]    7    8
[3,]    2    6

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

Objective 1: Find the minimum of each rows of each element. Expected output [[1]]-> 1,2,3 [[2]]-> 1,7,2 [[3]]-> 2,4,2

Objective 2: Find the corresponding column numbers. Expected output [[1]]-> 1,2,4 [[2]]-> 2,1,1 [[3]]-> 2,2,1

***NOTE that in [[3]][3,] there are two minimum numbers, one in column 1 and other in column 5. In such case, only report the column that comes first.

Objective 3: Find the sum of the output found in objective 1 separately for each list. Expected outcome [[1]]-> 6 [[2]]-> 10 [[3]]-> 8

I am looking for a general solution applicable to a much larger list than the example provided.

Upvotes: 1

Views: 41

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 102760

Here is a base R option using pmin

> lapply(list.mat, function(x) do.call(pmin, data.frame(x)))
[[1]]
[1] 1 2 3

[[2]]
[1] 1 7 2

[[3]]
[1] 2 4 2

Upvotes: 1

akrun
akrun

Reputation: 887941

We could use dapply from collapse which could be faster

library(collapse)
lapply(list.mat, dapply, fmin, MARGIN = 1)
#[[1]]
#[1] 1 2 3

#[[2]]
#[1] 1 7 2

#[[3]]
#[1] 2 4 2

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389315

You can use lapply :

output1 <- lapply(list.mat, function(x) apply(x, 1, min))
output1

#[[1]]
#[1] 1 2 3

#[[2]]
#[1] 1 7 2

#[[3]]
#[1] 2 4 2

output2 <- lapply(list.mat, function(x) apply(x, 1, which.min))
output2

#[[1]]
#[1] 1 2 4

#[[2]]
#[1] 2 1 1

#[[3]]
#[1] 2 2 1

output3 <- lapply(output1, sum)
output3

#[[1]]
#[1] 6

#[[2]]
#[1] 10

#[[3]]
#[1] 8

You can put the code in a function if you want to apply this for multiple such lists.

Upvotes: 2

Related Questions