Subset rows based on their integer locations, R has the slice() function, which allows you to subset rows according to their integer places.
Statistical test assumptions and requirements – Data Science Tutorials
The following techniques can be used to subset specific rows in a data frame:
Approach 1: Subset One Particular Row
get row 3 only
df %>% slice(3)
Approach 2: Subset Several Rows
get rows 2, 4, and 5
df %>% slice(2, 4, 5)
Approach 3: Subset A Range of Rows
get rows 1 through 3
How to Count Distinct Values in R – Data Science Tutorials
df %>% slice(1:3)
Approach 4: Subset Rows by Group
get the first row by group
df %>% Â group_by(var1) %>% Â slice(1)
The examples below demonstrate each technique using the given data frame:
put up a dataset
df <- data.frame(player = c('P1', 'P2', 'P3', 'P4', 'P5'), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â position = c('A', 'B', 'A', 'B', 'B'), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â points = c(102, 215, 319, 125, 112), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â assists = c(22, 12, 19, 23, 36))
Now we can view the dataset
df
player position points assists 1Â Â Â Â P1Â Â Â Â Â Â Â AÂ Â Â 102Â Â Â Â Â 22 2Â Â Â Â P2Â Â Â Â Â Â Â BÂ Â Â 215Â Â Â Â Â 12 3Â Â Â Â P3Â Â Â Â Â Â Â AÂ Â Â 319Â Â Â Â Â 19 4Â Â Â Â P4Â Â Â Â Â Â Â BÂ Â Â 125Â Â Â Â Â 23 5Â Â Â Â P5Â Â Â Â Â Â Â BÂ Â Â 112Â Â Â Â Â 36
Approach 1: Subset One Specific Row
To choose only Row 3 in the data frame using the slice() function, use the following code.
How to Rank by Group in R? – Data Science Tutorials
get row 3 only
df %>% slice(3)
player position points assists 1Â Â Â Â P3Â Â Â Â Â Â Â AÂ Â Â 319Â Â Â Â Â 19
Approach 2: Subset Several Rows
The slice() function can be used to pick out a few particular rows from the data frame by using the following code.
Remove Rows from the data frame in R – Data Science Tutorials
get rows 2, 4, and 5
df %>% slice(2, 4, 5)
player position points assists 1Â Â Â Â P2Â Â Â Â Â Â Â BÂ Â Â 215Â Â Â Â Â 12 2Â Â Â Â P4Â Â Â Â Â Â Â BÂ Â Â 125Â Â Â Â Â 23 3Â Â Â Â P5Â Â Â Â Â Â Â BÂ Â Â 112Â Â Â Â Â 36
Approach 3: Subset A Range of Rows
To select all rows in the range of 1 through 3, use the slice() function as demonstrated in the code below:
get rows 1 through 3
df %>% slice(1:3)
player position points assists 1Â Â Â Â P1Â Â Â Â Â Â Â AÂ Â Â 102Â Â Â Â Â 22 2Â Â Â Â P2Â Â Â Â Â Â Â BÂ Â Â 215Â Â Â Â Â 12 3Â Â Â Â P3Â Â Â Â Â Â Â AÂ Â Â 319Â Â Â Â Â 19
Approach 4: Subset Rows by Group
The slice() function can be used to select the first row in some groups, as demonstrated by the code below.
5 Free Books to Learn Statistics For Data Science – Data Science Tutorials
get the first row by group
df %>% Â group_by(player) %>% Â slice(1)
player position points assists  <chr> <chr>    <dbl>  <dbl> 1 P1    A          102     22 2 P2    B          215     12 3 P3    A          319     19 4 P4    B          125     23 5 P5    B          112     36