Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return row number(s) for a particular value in a column in a dataframe

I have a data frame (df) and I was wondering how to return the row number(s) for a particular value (2585) in the 4th column (height_chad1) of the same data frame?

I've tried:

row(mydata_2$height_chad1, 2585) 

and I get the following error:

Error in factor(.Internal(row(dim(x))), labels = labs) :    a matrix-like object is required as argument to 'row' 

Is there an equivalent line of code that works for data frames instead of matrix-like objects?

Any help would be appreciated.

like image 932
pkg77x7 Avatar asked Jan 09 '14 06:01

pkg77x7


People also ask

How do you get the row number in a value in a Dataframe?

Get Number of Rows in DataFrame You can use len(df. index) to find the number of rows in pandas DataFrame, df. index returns RangeIndex(start=0, stop=8, step=1) and use it on len() to get the count.

How do I return a row number in a value in R?

The dataframe column can be referenced using the $ symbol, which finds its usage as data-frame$col-name. The which() method is then used to retrieve the row number corresponding to the true condition of the specified expression in the dataframe. The column values are matched and then the row number is returned.

How do you find the index of a value in a Dataframe in R?

Data Visualization using R Programming For example, if we have a data frame called df that contains a value say Data then we can find the row and column index of Data by using the command as which(df=="Data",arr. ind=TRUE).

How do I find a specific row in R?

To get a specific row of a matrix, specify the row number followed by a comma, in square brackets, after the matrix variable name. This expression returns the required row as a vector.


2 Answers

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),                  y = c(5,4,6,7,8,3,2,4)) df   x y 1 1 5 2 1 4 3 2 6 4 3 7 5 4 8 6 5 3 7 6 2 8 3 4  which(df$x == 3) [1] 4 8  length(which(df$x == 3)) [1] 2  count(df, vars = "x")   x freq 1 1    2 2 2    1 3 3    2 4 4    1 5 5    1 6 6    1  df[which(df$x == 3),]   x y 4 3 7 8 3 4 

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

like image 170
SethB Avatar answered Sep 29 '22 15:09

SethB


which(df==my.val, arr.ind=TRUE)

like image 26
ivan866 Avatar answered Sep 29 '22 17:09

ivan866