user2662565
user2662565

Reputation: 529

R: Index corresponding to maximum value in each row

I have a 744 x 3 matrix (named sharpe_a) that I am looping over to create a dataframe composed of the index value corresponding to the maximum for each row (named last_bestIndex_colnum)

The issue is that it is treating two values with identical absolute value but opposite signs as equivalents.

        sr_sig_fx sr_comm_i sr_comm_ii
[1,]        NA        NA         NA
[2,]        NA    0.2632    -0.5714
[3,]   -0.3684    0.3684    -0.2222
[4,]    0.3846   -0.3846    -0.5000

so when using grep to identify the column containing the maximum value for row 3, for example, I get the following

> grep(max(x[3,]),x[3,])
[1] 1 2

so instead of just returning 2, it thinks -0.3684 and 0.3684 are the same value so are returning 1 and 2. However, I test x[3,1] > x[3,2] and it returns "FALSE", then x[3,1] < x[3,2] and it returns "TRUE" so I am assuming that grep and max are doing something to x but I am not sure what or why.

structure(c(NA, NA, -0.3684, 0.3846, 0.7, 0.7, 0.7895, 0.9412, 
0.55, 0.25, NA, 0.2632, 0.3684, -0.3846, -0.7, -0.7, -0.7895, 
-0.9412, -0.55, -0.25, NA, -0.5714, -0.2222, -0.5, -0.7, -0.7, 
-0.7895, -1, -0.8235, -1), .Dim = c(10L, 3L), .Dimnames = list(
    NULL, c("sr_sig_fx", "sr_comm_i", "sr_comm_ii")))

Upvotes: 0

Views: 140

Answers (1)

djfinnoy
djfinnoy

Reputation: 595

When you use grep like that, it correctly identifies 0.3684 as the maximum, then returns all columns that contain 0.3684, irregardless of the negative; grep is meant for strings. Try:

which(x[1,] == max(x[1,][!is.na(x[1,]))

Edit: Just noticed in the comments that you want to return NA when there is a tie between two values. This could be accomplished like so:

result <- which(x[1,] == max(x[1,][!is.na(x[1,]))
result <- ifelse(length(result) > 1, NA, result)

Upvotes: 3

Related Questions