[r] How to find row number of a value in R code

In the following set of values how can I find the row number of a particular value in column 4 ??

For example how can I find the row number of the value "1578" that's in column number 4 using the R code commands.

> mydata_2
   sex age height_seca1 height_chad1 height_DL weight_alog1
1    F  19         1800         1797       180         70.0
2    F  19         1682         1670       167         69.0
3    F  21         1765         1765       178         80.0
4    F  21         1829         1833       181         74.0
5    F  21         1706         1705       170        103.0
6    F  18         1607         1606       160         76.0
7    F  19         1578         1576       156         50.0
8    F  19         1577         1575       156         61.0
9    F  21         1666         1665       166         52.0
10   F  17         1710         1716       172         65.0
11   F  28         1616         1619       161         65.5
12   F  22         1648         1644       165         57.5
13   F  19         1569         1570       155         55.0
14   F  19         1779         1777       177         55.0
15   M  18         1773         1772       179         70.0
16   M  18         1816         1809       181         81.0
17   M  19         1766         1765       178         77.0
18   M  19         1745         1741       174         76.0
19   M  18         1716         1714       170         71.0
20   M  21         1785         1783       179         64.0
21   M  19         1850         1854       185         71.0
22   M  31         1875         1880       188         95.0
23   M  26         1877         1877       186        105.5
24   M  19         1836         1837       185        100.0
25   M  18         1825         1823       182         85.0
26   M  19         1755         1754       174         79.0
27   M  26         1658         1658       165         69.0
28   M  20         1816         1818       183         84.0
29   M  18         1755         1755       175         67.0

This question is related to r statistics

The answer is


(1:nrow(mydata_2))[mydata_2[,4] == 1578]

Of course there may be more than one row with a value of 1578.


As of R 3.3.0, one may use startsWith() as a faster alternative to grepl():

which(startsWith(mydata_2$height_seca1, 1578))

If you want to know the row and column of a value in a matrix or data.frame, consider using the arr.ind=TRUE argument to which:

> which(mydata_2 == 1578, arr.ind=TRUE)
  row col
7   7   3

So 1578 is in column 3 (which you already know) and row 7.


Instead of 1:nrow(mydata_2) you can simply use the which() function: which(mydata_2[,4] == 1578)

Although as it was pointed out above, the 3rd column contains 1578, not the fourth: which(mydata_2[,3] == 1578)