Specific Rows

We wish to obtain specific rows of a data frame by specifying their positions (row number).

Specific Rows

We wish to get specific rows from a data frame by specifying their position.

df_2 = df %>% slice(2, 4, 8)

Here is how this works:

  • We pass the data frame df to the function slice().
  • slice() can take a comma separated list of row positions and returns the corresponding rows. In this example, the rows at positions 2, 4 and 8.

Selected Columns

Get the specific rows of a data frame including only a selected set of columns.

df_2 = df %>% select(col_1, col_3) %>% slice(2, 4, 8)
  • We use select() to specify the column names of the columns of the data frame df that we wish to include in the output. In this example, the column names are col_1 and col_3. For a detailed coverage, see Selecting by Name.
  • We then pass the output of select() to slice() to get the rows at the specified positions.

Single Value

We wish to obtain the value of a particular column at a particular row. In this example we wish to obtain the value of col_1 at row 3.

val = df %>% slice(3) %>% pull(col_1)

Here is how this works:

  • We pass the position of the row of interest to slice() to extract a data frame of one row. In this example, slice(3) extracts the third row or the original data frame df.
  • We then use pull(col_1) to extract the value of col_1 and return that as scalar numerical variable.
R
I/O