Skip to content

Using slice() with a row number vector which includes 0 results in wrong output #3313

@huftis

Description

@huftis

If one uses slice() with a row number vector which includes 0 and other row numbers, wrong output is produced. Here’s a repexp:

library(dplyr)

# Example data
d = tibble(x = 1:5, y = LETTERS[1:5])

# This command works fine (returns a zero-row subset)
slice(d, 0)
#> # A tibble: 0 x 2
#> # ... with 2 variables: x <int>, y <chr>

# But these commands give incorrect output
slice(d, c(0, 1))
#> # A tibble: 1 x 2
#>       x y    
#>   <int> <chr>
#> 1    NA <NA>
slice(d, c(0, 1, 2))
#> # A tibble: 2 x 2
#>       x y    
#>   <int> <chr>
#> 1    NA <NA> 
#> 2     1 A
slice(d, c(-1, 0))
#> # A tibble: 3 x 2
#>       x y    
#>   <int> <chr>
#> 1     3 C    
#> 2     4 D    
#> 3     5 E
slice(d, c(0, -1))
#> # A tibble: 3 x 2
#>       x y    
#>   <int> <chr>
#> 1     3 C    
#> 2     4 D    
#> 3     5 E

# Subsetting using base R functions works fine, i.e. gives the expected output
d[0, ]
#> # A tibble: 0 x 2
#> # ... with 2 variables: x <int>, y <chr>
d[c(0, 1), ]
#> # A tibble: 1 x 2
#>       x y    
#>   <int> <chr>
#> 1     1 A
d[c(0, 1, 2), ]
#> # A tibble: 2 x 2
#>       x y    
#>   <int> <chr>
#> 1     1 A    
#> 2     2 B
d[c(-1, 0), ]
#> # A tibble: 4 x 2
#>       x y    
#>   <int> <chr>
#> 1     2 B    
#> 2     3 C    
#> 3     4 D    
#> 4     5 E
d[c(0, -1), ]
#> # A tibble: 4 x 2
#>       x y    
#>   <int> <chr>
#> 1     2 B    
#> 2     3 C    
#> 3     4 D    
#> 4     5 E

Metadata

Metadata

Labels

bugan unexpected problem or unintended behavior

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions