Subset data using disjoint line numbers

I have a data frame with 30 rows and 100 columns (X).

I would like to create a new data frame (Y) with specific rows from a larger data frame.

For example, I would like the data frame (Y) to contain rows 1 through 5, from 10 to 14 and 20.

I know I can use the code:

Y<-X[1:5,] 

and get the first five lines, but I can't develop similar code to get lines 1: 5, 10:14 and 20.

+7
source share
1 answer

Typically, the familiar X [rows, cols] format is used when selecting rows in a data frame or matrix. It is useful to remember that both parameters can be generated not just as primes or sequences, but also by concatenating numbers and sequences. So for your problem, you can use something like the following:

 Y <- X[c(1:5, 10:14, 20), ] 

This will select rows 1 through 5, rows 10 through 14, and row 20 along with all the columns in X and assign the result to Y.

+13
source

All Articles