rahul rajput
rahul rajput

Reputation: 35

How to access a row in a data frame by using first column values in R

    intercatedData                 n

1 Completed Degree in 2 Years.0    2
2  Retained to Midyear Year 2.0    1
3 Retained to Start of Year 2.0    1
4  Retained to Midyear Year 2.1    1
5 Retained to Start of Year 2.1    1

Here is the data frame(mydf) that i am using.

Now i want access first row value (that is 2) by its name (Completed Degree in 2 Years.0). I am able to access the value by using print(mydf$n[1]) but right I would like to access the value by name instead of by index 1.

How can I access the value by name instead of by index ?

Upvotes: 1

Views: 1649

Answers (1)

Ajay Ohri
Ajay Ohri

Reputation: 3492

mydf[ mydf$intercatedData == 'Completed Degree in 2 Years.0', ]

A DATA record in a dataframe has a row AND column and so can be referred as so

mydf[2,3] will give me record in 2nd row and 3rd column for dataframe named mydf

mydf[2,] will give me record in 2nd row and all columns for that for dataframe named mydf

mydf[,3] will give me records in 3rd column for dataframe named mydf

This dataframe property can now be used for conditional selection

mydf[ mydf$intercatedData == 'Completed Degree in 2 Years.0', ]

Says give me all rows where the value for mydf$intercatedData is 'Completed Degree in 2 Years.0' and all columns

Upvotes: 1

Related Questions