Mike
Mike

Reputation: 1069

R: Applying function to specific rows only

I'm trying to apply a function only to certain rows which meet my conditions. I've seen from other threads that I should use the "apply" function, but I can't seem to get it to work.
Here is what I have so far:

a = which(decisionMatrix[,1]>0 & decisionMatrix[,4] < decisionMatrix[,5] &
          tail(ratios,1)>decisionMatrix[4])

Which gives me the numbers of the rows which meet my conditions.

I then use:

apply(decisionMatrix[10],a,decisionMatrix[,1]/decisionMatrix[,5])

What I'm trying to do here is say "for each row that meets the above conditions, take the first column in that row and divide it by the fifth column in that row and store the result in the 10th column of that row"

Would anyone be able to give me some advice?

Upvotes: 1

Views: 10878

Answers (2)

Thomas
Thomas

Reputation: 44525

Following Ananda's comment, you want something like:

apply(decisionMatrix[a,], 1, function(x) x[1]/x[5])

But if you want the output to be something of the same dimensions as your input (e.g., if you're going to add it back to the original decisionMatrix object), you may instead want to apply the function to every row, but then subset its output:

out <- apply(decisionMatrix, 1, function(x) x[1]/x[5])
out[-a] <- NA

As @agstudy points out the latter can be vectorized by just doing

out <- decisionMatrix[,1]/decisionMatrix[,5]

But you may have a more complicated operation for which that solution would not work. If it works with your operation, the vectorized solution is cleaner and faster.

You may also want to store this back into your original decisionMatrix and doing so depends on the structure of your original decisionMatrix:

# If you want to replace an existing column 10:
decisionMatrix[,10] <- out

# If you want to column bind the result back to your original matrix:
decisionMatrix <- cbind(decisionMatrix, out)

Upvotes: 3

flodel
flodel

Reputation: 89057

Don't use apply. To modify the rows in-place, just do:

decisionMatrix[a, 10] <- decisionMatrix[a, 1] / decisionMatrix[a, 5]

Upvotes: 5

Related Questions