Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select some rows with specific rownames from a dataframe? [closed]

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 
like image 662
user2405694 Avatar asked Sep 21 '13 13:09

user2405694


People also ask

How do I select specific rows from a DataFrame in R?

By using bracket notation on R DataFrame (data.name) we can select rows by column value, by index, by name, by condition e.t.c. You can also use the R base function subset() to get the same results. Besides these, R also provides another function dplyr::filter() to get the rows from the DataFrame.

How do I filter row names in R?

Filter Data Frame Rows by Row Number In order to filter data frame rows by row number or positions in R, we have to use the slice() function. this function takes the data frame object as the first argument and the row number you wanted to filter.


2 Answers

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.

like image 127
maj Avatar answered Sep 23 '22 09:09

maj


You can also use this:

DF[paste0("stu",c(2,3,5,9)), ] 
like image 35
Ferdinand.kraft Avatar answered Sep 23 '22 09:09

Ferdinand.kraft