How can I select a row by row name in a subsetted

2019-07-21 07:23发布

问题:

I want to select rows by name in a data frame that is a subset of a larger one. The subsetted data frame appears to have retained the names of the original data frame, such that:

> DFsubset[1:3,]

       x1    x2    x3
271    3     5      2
553    2     4      1
563    2     5      3

while using the printed row name returns the following:

> DFsubset[271,]
Error in xj[i, , drop = FALSE] : subscript out of bounds

How can I select these rows based on the row names from the original DF, ie. 271, 553, 563?

回答1:

You need to reference the rownames of your data.frame:

dfsub[rownames(dfsub) == 271,] #where dfsub is your subsetted data.frame

EDIT:

as @koekenbakker commented, there is a shorthand to reference the rownames by using ''. So this would be:

dfsub['271',] #where dfsub is your subsetted data.frame and 271 the rowname


标签: r subset