Skip to content

Instantly share code, notes, and snippets.

@olivroy
Last active May 3, 2024 13:06
Show Gist options
  • Select an option

  • Save olivroy/1f75344ef3c0d2669949db1f2724434c to your computer and use it in GitHub Desktop.

Select an option

Save olivroy/1f75344ef3c0d2669949db1f2724434c to your computer and use it in GitHub Desktop.
mat <- matrix(
  c(1, 2, 3, 4),
  nrow = 2
)
mat
#>      [,1] [,2]
#> [1,]    1    3
#> [2,]    2    4
indice <- integer(0) # mimic `which()` result if nothing found.
mat[-1, ] # Returns a vector... why drop = TRUE is the default? 
#> [1] 2 4
mat[-1, , drop = FALSE] # returns matrix. correctly drops first row
#>      [,1] [,2]
#> [1,]    2    4
mat[-indice, , drop = FALSE]
#>      [,1] [,2]

df <- data.frame(x = c(1, 2), y = c(1, 2))
df
#>   x y
#> 1 1 1
#> 2 2 2
df[-1, ] # correctly returns the first row
#>   x y
#> 2 2 2
df[-indice, ] # drop = FALSE is the default
#> [1] x y
#> <0 rows> (or 0-length row.names)
df[-indice, , drop = FALSE] # works okay too
#> [1] x y
#> <0 rows> (or 0-length row.names)
df[-indice, , drop = TRUE] # same as matrix
#> [1] x y
#> <0 rows> (or 0-length row.names)

Created on 2024-05-03 with reprex v2.1.0

@olivroy
Copy link
Author

olivroy commented May 3, 2024

Not better for df, removes everything.. same with tibble.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment