How can I select a row by row name in a subsetted data frame in R?

▼魔方 西西 提交于 2019-12-31 03:41:08

问题


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


来源:https://stackoverflow.com/questions/23652566/how-can-i-select-a-row-by-row-name-in-a-subsetted-data-frame-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!