47

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.

FXQuantTrader
  • 6,221
  • 3
  • 31
  • 62
pkg77x7
  • 795
  • 2
  • 6
  • 10

2 Answers2

84

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.

Community
  • 1
  • 1
SethB
  • 1,820
  • 12
  • 16
  • 1
    and if wanted to find the number of times the value 2585 occurred in the same column would I use a similar construct with the function count? count(mydata_2$height_chad1 == 2585) – pkg77x7 Jan 09 '14 at 06:56
  • 2
    You could use `length` on the result of the answer provided by Seth or use `sum` instead of `count` in your suggestion. Have you tried the `count` function as you suggest? It's an easy one to test with no danger of breaking anything...! – Matt Weller Jan 09 '14 at 10:49
  • 1
    Nice solution, but what if you don't just want to look at the x column, what if you want to return the row&col values for each cell in the data frame which equals 3? – Parsa Jul 06 '16 at 11:09
  • 1
    @par Try `df[which(df$x == 3),]` This returns the [rows,colums]. Leaving one blank indicates all. – SethB Jul 06 '16 at 14:46
  • I was searching for how to be selective with columns and yet get the results with row ids of the data.frame. I found an answer to this in my case to get just four columns from @SethB's answer. df[which(df$x == 3),1:4] – Unnikrishnan Feb 27 '21 at 12:58
1

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

ivan866
  • 361
  • 3
  • 10
  • 3
    while this could be the right answer it's alway better to add some explanation of what you code does... can you please add some? – DaFois Oct 06 '20 at 22:35
  • i believe we need at least 2 more votes by other moderators who think a question that simple needs answers with explanations, considering the source code is self-documented; otherwise, the moderator who groundlessly demands such improvements himself desires explaining his actions – ivan866 Oct 07 '20 at 11:47