top_n_row: Utility functions for finding top-ranking row/column elements

top_n_rowR Documentation

Utility functions for finding top-ranking row/column elements

Description

One often wants to know which are the largest n elements in each of the rows or columns of a matrix. These functions extract the indices of these elements (using naive ranking).

Usage

top_n_row(m, n)

top_n_col(m, n)

Arguments

m

matrix

n

number of elements to extract. Unlike dplyr's top_n, no account is taken here of the possibility that the nth element is tied with the (n + 1)th (etc).

Value

a two-column subscript matrix with row indices in the first column and column indices in the second. This can be used as a single subscript to the input matrix m to yield a vector.

Examples

m <- matrix(1:9, ncol=3)
ij_row <- top_n_row(m, 2)
ij_col <- top_n_col(m, 2)

# note the resulting grouping by rows/cols
m[ij_row]
m[ij_col]
data.frame(rownum=ij_row[ , 1], value=m[ij_row])


agoldst/dfrtopics documentation built on July 15, 2022, 4:13 p.m.