Use ifelse to extract information from a matrix
I am trying to extract some information from a table and I am trying to avoid any loops or use type functions.
Suppose that the 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 matrices 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 to check for each element m whether the sum g [, 1] + g [, 2] is equal to this element. For all cases where the condition is TRUE, I want my code to return the position of the one with the largest g [, 3] value. For example, when m = 5, the condition x [, 1] + x [, 2] == 5 is TRUE at 15,16,17,18,19 and 20. Of this 6, entry 17 has the highest value, so I want my code to return value 17.
So, in the end, I would expect a vector length = length (m), which will indicate for each element 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, string, where g [, 1] + g [, 2] == 1, is string 1, when m = 2 string, where g [, 1] + g [, 2] == 2 - line 4, etc.
I am currently using application on each line of g, but this process is repeated thousands of times and my code is very slow. To speed things up, I resorted to ifelse to do something in the vector.
I am trying to do the following:
ifelse(m>0,which(g[,3]==max(g[which(g[,1]+g[,2]==m),3])),0)
When I run this I get
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
and if you substitute m for 5, it returns a vector of 17s. It seems like it only uses the first element of m instead of the whole vector. Any suggestions on how I can get this job done, or an alternative that can do the same job, is more than welcome.
source to share