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?
cderv
November 25, 2019, 8:21pm
4
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
system
Closed
December 2, 2019, 8:33pm
5
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.