Subset DataFrame and Matrix by Row Names in R
In this article, we are going to see how to evaluate subset dataframe and matrices by row name.
Method 1: Subset dataframe by row names
The rownames(df) method in R is used to set the names for rows of the data frame. A vector of the required row names is specified. The %in% operator in R is used to check for the presence of the data frame row names in the vector of required row names. The rows of the data frame are then retrieved from the data frame if they occur in the vector. The row names are returned in the final output of the data frame. The output is then used to return a subset of the data frame rows.
Syntax: val %in% vec
- val – A list or vector of values to check in vector
- vec – A vector to check the values in
Method 2: Subset matrix by row names
The rownames(mat)method in R is used to set the names for rows of the matrix. A similar approach is used to check for the presence of row names of the matrix in the vector or list of specified row names. The following code snippet can be used to subset the matrix based on the specified row names.
Please Login to comment...