Accessing columns, rows, or cells via $, [[, or [ is mostly similar to regular data frames. However, the behavior is different for tibbles and data frames in some cases:

  • [ always returns a tibble by default, even if only one column is accessed.

  • Partial matching of column names with $ and [[ is not supported, a warning is given and NULL is returned.

Unstable return type and implicit partial matching can lead to surprises and bugs that are hard to catch. If you rely on code that requires the original data frame behavior, coerce to a data frame via as.data.frame().

# S3 method for tbl_df
[[(x, i, j, ..., exact = TRUE)

# S3 method for tbl_df
$(x, name)

# S3 method for tbl_df
[(x, i, j, drop = FALSE)

Arguments

x

data frame.

i, j

Row and column indices. If j is omitted, i is used as column index.

...

Ignored.

exact

Ignored, with a warning.

name

A literal character string or a name (possibly backtick quoted).

drop

Coerce to a vector if fetching one column via tbl[, j] . Default FALSE, ignored when accessing a column via tbl[j] .

Details

For better compatibility with older code written for regular data frames, [ supports a drop argument which defaults to FALSE. New code should use [[ to turn a column into a vector.

Examples

df <- data.frame(a = 1:3, bc = 4:6) tbl <- tibble(a = 1:3, bc = 4:6) # Subsetting single columns: df[, "a"]
#> [1] 1 2 3
tbl[, "a"]
#> # A tibble: 3 x 1 #> a #> <int> #> 1 1 #> 2 2 #> 3 3
tbl[, "a", drop = TRUE]
#> [1] 1 2 3
as.data.frame(tbl)[, "a"]
#> [1] 1 2 3
# Subsetting single rows with the drop argument: df[1, , drop = TRUE]
#> $a #> [1] 1 #> #> $bc #> [1] 4 #>
tbl[1, , drop = TRUE]
#> # A tibble: 1 x 2 #> a bc #> <int> <int> #> 1 1 4
as.list(tbl[1, ])
#> $a #> [1] 1 #> #> $bc #> [1] 4 #>
# Accessing non-existent columns: df$b
#> [1] 4 5 6
tbl$b
#> Warning: Unknown or uninitialised column: 'b'.
#> NULL
df[["b", exact = FALSE]]
#> [1] 4 5 6
tbl[["b", exact = FALSE]]
#> Warning: exact ignored
#> NULL
df$bd <- c("n", "e", "w") tbl$bd <- c("n", "e", "w") df$b
#> NULL
tbl$b
#> Warning: Unknown or uninitialised column: 'b'.
#> NULL
df$b <- 7:9 tbl$b <- 7:9 df$b
#> [1] 7 8 9
tbl$b
#> [1] 7 8 9
# Identical behavior: tbl[1, ]
#> # A tibble: 1 x 4 #> a bc bd b #> <int> <int> <chr> <int> #> 1 1 4 n 7
tbl[1, c("bc", "a")]
#> # A tibble: 1 x 2 #> bc a #> <int> <int> #> 1 4 1
tbl[, c("bc", "a")]
#> # A tibble: 3 x 2 #> bc a #> <int> <int> #> 1 4 1 #> 2 5 2 #> 3 6 3
tbl[c("bc", "a")]
#> # A tibble: 3 x 2 #> bc a #> <int> <int> #> 1 4 1 #> 2 5 2 #> 3 6 3
tbl["a"]
#> # A tibble: 3 x 1 #> a #> <int> #> 1 1 #> 2 2 #> 3 3
tbl$a
#> [1] 1 2 3
tbl[["a"]]
#> [1] 1 2 3