why is an indexed tibble cell has the class of tibble?

Lately I realized that an indexed tibble cell has the clas of a tibble. I do not understand the logic behind the decision. Can you explain it to me?

library(tibble)
mtcars_tibble <- as_tibble(mtcars)
class(mtcars_tibble[1,2])
# gives back tibble

mtcars_dataframe <- as.data.frame(mtcars)
class(mtcars_dataframe[1,2])
# gives back numeric

The reason is that tibbles are designed to return consistent output. See e.g. to explain the single-column behaviour:

What you might think of as single cells from a dataframe (as in your example) are actually single-element vectors. R doesn't have scalars.

2 Likes

Thanks for the detailed response Martin!

So I should just stick to filter() and pull() if I need a specific cell? Or what is the best practice?

Let just add that data.frame is dropping by default and tibble is not.
However you can use drop = TRUE if you really need to get numeric and not a tibble.

library(tibble)
mtcars_tibble <- as_tibble(mtcars)
class(mtcars_tibble[1,2, drop = TRUE])
#> [1] "numeric"

In tidyverse, pull is here to extract what is inside a tibble and would be the best pratice.

See

?`[` 

and

?tibble::`[.tbl_df`
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.