首页 > 解决方案 > tibble and dataframe, function

问题描述

mat_iris <- as.matrix(iris)

tidyr::as_tibble(mat_iris)
tibble::as_tibble(mat_iris)


tidyr background work tibble ?

dplyr::tbl_df(mat_iris)
dplyr::as_data_frame(mat_iris)

What's the difference two ?  

https://www.rdocumentation.org/packages/dplyr/versions/0.5.0/topics/tbl_df https://www.rdocumentation.org/packages/tibble/versions/1.0/topics/as_data_frame

标签: rtidyverse

解决方案


I think some of your confusion is about the difference between tibbles and data.frames. Tibbles are a special class of data.frame. Tibbles add increased functionality to data.frames, like improved printing by providing the data type in each column when printed. Tibbles also default to printing only the first ten rows, and make some adjustments based on the width of the output console.

Compare what happens in the console when you print mtcars versus tibble(mtcars).

Another difference is that tibbles are stricter when you ask them to do something, like subsetting. Compare what happens when you ask mtcars for a column that does not exist.

# data.frame
mtcars$bounce
NULL

# tibble
tibble(mtcars)$bounce
NULL
Warning message:
Unknown or uninitialised column: `bounce`. 

The tibble kindly informs you that you asked for something that does not exist.

One last difference is that tibbles can have columns where the entries are not values, but vectors, lists, and other data.frames.

Read more about the difference at this blog entry.

As for the specific functions: as_tibble() converts something to a tibble. The functions tibble::as_tibble, dplyr::as_tibble and tidyr::as_tibble are all the same function. The function is from the tibble package, but it has been exported to dplyr and tidyr so you can use it in those packages without needing to load tibble.

The tbl_df() function from dplyr is a legacy function for dplyr to use to coerce things into tibbles. The documentation page for tbl_df() indicated that this function has been superseded by as_tibble(). You should use as_tibble(), but tbl_df() remains in the package for reverse compatibility.

The as_data_frame() function is a deprecated function for columnwise construction of tibbles that has been replaced by as_tibble(). I am using tibble v 3.0.3 and dplyr v 1.0.1, and I get prevented from trying use as_data_frame() with a warning message to to use as_tibble() instead.


推荐阅读