matrix - Subsetting by row condition in R -


i'm trying work out way of subsetting matrix purely numeric (i.e. no column/row names). put in form of worked example, drop rows not meet logical condition.

set.seed(42) m <- matrix(sample.int(100, 10*10, true), 10, 10) 

say want make subset keep rows maximum row value 90 or over, drop not meet condition.

the way can think of doing through if/else loop (max(m[i,]) > 90) feel there must more elegant way of doing this.

any ideas?

you can in several steps.

first, find maxima of rows using apply on rows:

maxima = apply(m, 1, max) # [1] 92 99 99 98 93 96 98 91 98 84 

next, greater threshold:

above = maxima >= 90 # [1]  true  true  true  true  true  true  true  true  true false 

now, use subset data:

m[above, ] 

or, in 1 line:

m[apply(m, 1, max) >= 90, ] 

you can expand condition arbitrarily. instance, test whether maximum between 2 values, can this:

between = function (x, lower, upper)     x >= lower & x <= upper  m[between(apply(m, 1, max), 90, 97), ] 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -