user695652
user695652

Reputation: 4275

Get data.frame row by ID

I have a data.frame $X$ obtained from a data.frame $Y$ by filtering out some rows. I am now interested in accessing a row with ID $i$ (By ID I mean the value appearing in the very first column, generated by R). I am only aware of the $X[i,]$ command, which, as far as I understand, gives me the $i$-th row in $X$ but not the row with ID $i$.

Is there any other command to access a row by its id?

Upvotes: 4

Views: 9735

Answers (2)

Maxim.K
Maxim.K

Reputation: 4180

As an alternative, you can use quotes "" to refer to a given row by its respective element of rownames(),e.g.:

X["35",]

Upvotes: 6

vinux
vinux

Reputation: 965

You could use row.names(X) to access the ID information. Example is given below.

X <- subset(airquality, Temp > 80, select = c(Ozone, Temp))
X$id <- row.names(X)
head(X)
        #   Ozone Temp id
        #29    45   81 29
        #35    NA   84 35
        #36    NA   85 36
        #38    29   82 38
        #39    NA   87 39
        #40    71   90 40
X[X$id==35,]
        #   Ozone Temp id
        #35    NA   84 35

Upvotes: 1

Related Questions