Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get row index number in R?

Tags:

dataframe

r

Suppose I have a list or data frame in R, and I would like to get the row index, how do I do that? That is, I would like to know how many rows a certain matrix consists of.

like image 874
lesbegue's alter ego Avatar asked Mar 03 '10 10:03

lesbegue's alter ego


People also ask

How do I get rows indices in R?

You can try as. numeric(rownames(df)) if you haven't set the rownames. Otherwise use a sequence of 1:nrow(df) . The which() function converts a TRUE/FALSE row index into row numbers.

How do I display a row number in R?

To Generate Row number to the dataframe in R we will be using seq.int() function. Seq.int() function along with nrow() is used to generate row number to the dataframe in R. We can also use row_number() function to generate row index.

How do I find the row number in a matrix in R?

Getting a Matrix of number of rows in R Programming – row() Function. row() function in R Language is used to get the row number of a matrix.


Video Answer


2 Answers

I'm interpreting your question to be about getting row numbers.

  • You can try as.numeric(rownames(df)) if you haven't set the rownames. Otherwise use a sequence of 1:nrow(df).
  • The which() function converts a TRUE/FALSE row index into row numbers.
like image 105
Shane Avatar answered Sep 25 '22 15:09

Shane


It not quite clear what exactly you are trying to do.

To reference a row in a data frame use df[row,]

To get the first position in a vector of something use match(item,vector), where the vector could be one of the columns of your data frame, eg df$cname if the column name is cname.

Edit:

To combine these you would write:

df[match(item,df$cname),]

Note that the match gives you the first item in the list, so if you are not looking for a unique reference number, you may want to consider something else.

like image 31
James Avatar answered Sep 24 '22 15:09

James