Subset rows based on their integer locations-slice in R
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