I am trying to extract some information from a table and I am trying to avoid any *for* loops or *apply* type functions.

Assume a vector m

```
m=c(1:20)
m
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
```

and a matrix g

```
x1=c(0,1,0,1,2,0,1,2,3,0,1,2,3,4,0,1,2,3,4,5)
x2=c(1,0,2,1,0,3,2,1,0,4,3,2,1,0,5,4,3,2,1,0)
u=.4*x1^.5+.6*x2^.5
g=cbind(x1,x2,u)
g
x1 x2 u
[1,] 0 1 0.6000000
[2,] 1 0 0.4000000
[3,] 0 2 0.8485281
[4,] 1 1 1.0000000
[5,] 2 0 0.5656854
[6,] 0 3 1.0392305
[7,] 1 2 1.2485281
[8,] 2 1 1.1656854
[9,] 3 0 0.6928203
[10,] 0 4 1.2000000
[11,] 1 3 1.4392305
[12,] 2 2 1.4142136
[13,] 3 1 1.2928203
[14,] 4 0 0.8000000
[15,] 0 5 1.3416408
[16,] 1 4 1.6000000
[17,] 2 3 1.6049159
[18,] 3 2 1.5413485
[19,] 4 1 1.4000000
[20,] 5 0 0.8944272
```

I want for every element of m, to check if the sum g[,1]+g[,2] is equal to that element. For all the cases where the condition is TRUE, I want my code to return the position of the one which has the highest value of g[,3]. For example when m=5, the condition x[,1]+x[,2]==5 is TRUE at 15,16,17,18,19 and 20. Out of this 6, entry 17 has the highest value, so I want my code to return the value 17.

So at the end, I would expect a vector of length=length(m), that will indicate for each element of m, where is the maximum value of g[,3] that satisfies the above condition. The vector should be something like this:

```
1,4,7,11,17,0,0,0,0,0,0...,0
```

where when m=1, the row where g[,1]+g[,2]==1 is row 1 when m=2, the row where g[,1]+g[,2]==2 is row 4 and so on.

Currently I am using *apply* over each row of g, but this process is repeated thousands of times, and my code is very slow. To speed up things I resorted to *ifelse* in an effort to do things in a vectorised way.

What I am trying to do is the following:

```
ifelse(m>0,which(g[,3]==max(g[which(g[,1]+g[,2]==m),3])),0)
```

When I am running this I am getting

```
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
```

while if I substitute m with 5, it returns a vector of 17s. It seems that it only uses the first element of m instead of the whole vector. Any suggestions of how I can make this work, or an alternative that could do the same job is more than welcome.

rif-statementmatrixvectorization answered 7 months ago akrun #1

We could use `outer`

with `max.col`

```
m1 <- t(outer( g[,1] + g[,2], m, `==`)* g[,3])
max.col(m1) * (rowSums(m1!= 0) !=0)
#[1] 1 4 7 11 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
```