hsmith hsmith - 3 months ago 28
R Question

How to extract information on the two lowest elements of an r variable?

So my task is to "extract and display the soil types of the two lowest altitude plots using a single line of R code", and I'm not sure of the best way of doing this.

At the moment my command looks like this:

conservation$soil[conservation$alt < 8]

but that's because I know the two lowest altitude plots are below 8, so I'm kind of cheating.

Surely there's a simple way to just define the two lowest entries here instead?


You can order the lines of conservation$alt with order(conservation$alt) in a descending fashion. Or order(-conservation$alt) for the lines in ascending order.

tail(df$a, 2) will return the last two entries of df$a. Alternatively, head(df$a, 2) will give the first two entries.

Combining these functions will give you:

conservation$soil[tail(order(-conservation$alt), 2)]


conservation$soil[head(order(conservation$alt), 2)]