40

I have a data frame with several rows. I want to select some rows with specific rownames (such as stu2,stu3,stu5,stu9) from this dataframe. The input example dataframe is as follows:

        attr1 attr2 attr3 attr4
  stu1      0     0     1     0
  stu2     -1     1    -1     1
  stu3      1    -1     0    -1
  stu4      1    -1     1    -1
  stu5     -1     1     0     1
  stu6      1    -1     1     0
  stu7     -1    -1    -1     1
  stu8      1    -1     0    -1
  stu9     -1    -1     1    -1
  stu10    -1     1     0     1

Expected output:

        attr1 attr2 attr3 attr4
  stu2     -1     1    -1     1
  stu3      1    -1     0    -1
  stu5     -1     1     0     1
  stu9     -1    -1     1    -1
3
  • 34
    In my opinion the question is a valid one. The user has given the expected result. Yes, he seems to be a newbie with a minimal understanding of R but I believe that this shall not be held against him. After all, we are all noobs in some areas.
    – Nick
    Mar 27, 2015 at 21:00
  • sel = c('stu2', 'stu3', 'stu5', 'stu9') and df[sel,]
    – user2110417
    Jul 28, 2022 at 8:59
  • I came here because read.table automatically converted some names substituting dashes with dots, which I didn't notice. I did not understand why my row selection did not work and wanted to be sure I was not crazy and that I had not just dreamed the df[sel,] syntax based on some confusion with pandas. By the way, check.names = FALSE in read.table was the solution to my troubles.
    – bli
    Aug 2, 2022 at 14:22

3 Answers 3

63

Assuming that you have a data frame called students, you can select individual rows or columns using the bracket syntax, like this:

  • students[1,2] would select row 1 and column 2, the result here would be a single cell.
  • students[1,] would select all of row 1, students[,2] would select all of column 2.

If you'd like to select multiple rows or columns, use a list of values, like this:

  • students[c(1,3,4),] would select rows 1, 3 and 4,
  • students[c("stu1", "stu2"),] would select rows named stu1 and stu2.

Hope I could help.

1
  • 2
    if the rows and columns to be extracted are consecutive, then students[<staringRowNo.>:<endRowNo.>, <startColnNo.>:<endColNo.>] can also be used. eg; students[11:20, 2:10] selects rows 11 to 20 and columns 2 to 10. However, if row names or column names have to be specified, then students[c("rowname1", "rowname2", ...), c("colname1", "colname2"..] can be used. Sep 6, 2014 at 19:23
7

You can also use this:

DF[paste0("stu",c(2,3,5,9)), ]
4
df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <-  letters[1:10]
df[c('a','b'),]

Not the answer you're looking for? Browse other questions tagged or ask your own question.