user2277435
user2277435

Reputation: 245

Read only the first column whose row elements > 0 for every row within a matrix

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

Answers (1)

alexwhan
alexwhan

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

Related Questions