Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get Row Number for R data frame

Tags:

r

A question about data frames in R. I want to extract a row from a data frame, along with its position(row number) in the original data frame. The idea is to create a new data frame that includes the row information extracted from the previous data frame, as well as the row position from the previous data frame.

patchLocalNo <- patchList[which(patchListTop5$sensitivity == patchLocalSpec),]

what I want to do is take the row numbers from patchList that satisfy the which condition, and add them to a column in patchLocalNo.

Thank you in advance, I have searched online and asked co-workers and all I can come up with is a work-around pre-processing the data in perl.

like image 306
wespiserA Avatar asked Sep 11 '25 05:09

wespiserA


2 Answers

I think you have answered your own question.

The results of which() is a vector with the row numbers that you want to extract.

df <- data.frame(x = runif(20))

w <- which(df$x > 0.9)
w
[1]  9 11 14 16 20

data.frame(which=w, df=df[w, ])

  which        df
1     9 0.9437138
2    11 0.9995509
3    14 0.9237888
4    16 0.9526003
5    20 0.9191727
like image 91
Andrie Avatar answered Sep 12 '25 19:09

Andrie


You can do this in one or two lines of code:

rNo <- as.integer(rownames(patchList[which(patchListTop5$sensitivity == patchLocalSpec),]))
patchLocalNo <- cbind(patchLocalNo[rNames,], rNo)
like image 33
c.gutierrez Avatar answered Sep 12 '25 20:09

c.gutierrez