Reputation: 245
Original matrix below:
3 -1 4
0 2 1
Looking to get a vector containing the values: 3, 2. Only the elements in each row which are greater than 0, and only for the first column. Assume all rows contain at least one element > 0. Suggestions?
Upvotes: 1
Views: 68
Reputation: 16026
It seems like there should be something simpler, but here's an option:
#With mat as your matrix
apply(mat, 1, function(x) x[x > 0][1]) #@tonytonov's improvement
#[1] 3 2
Upvotes: 3