We wish to obtain specific rows of a data frame by specifying their positions (row number).
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:
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.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)
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.select()
to slice()
to get the rows at the specified positions.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:
slice()
to extract a data frame of one row. In this example, slice(3)
extracts the third row or the original data frame df
.pull(col_1)
to extract the value of col_1
and return that as scalar numerical variable.