as.tbl & is.tbl R Functions of dplyr Package (2 Examples)

 

In this article you’ll learn how to create and check tibbles with the as.tbl and is.tbl functions of the dplyr package in R.

The content looks as follows:

You’re here for the answer, so let’s get straight to the R syntax…

 

Creation of Example Data

The examples of this R tutorial are based on the following data frame in R:

my_data <- data.frame(x1 = 1:5,                 # Create example data
                      x2 = LETTERS[1:5],
                      x3 = 5)
my_data                                         # Print example data
#   x1 x2 x3
# 1  1  A  5
# 2  2  B  5
# 3  3  C  5
# 4  4  D  5
# 5  5  E  5

If we want to work with tibbles, we also need to install and load the dplyr package:

install.packages("dplyr")                       # Install dplyr
library("dplyr")                                # Load dplyr

 

Example 1: Convert Data Frame to Tibble with as.tbl Function

We can use the as.tbl function, if we want to convert a data frame to a tibble in R. Have a look at the following R code:

my_tbl <- as.tbl(my_data)                       # Convert data frame to tibble
my_tbl                                          # Print tibble
# # A tibble: 5 x 3
#      x1 x2       x3
#   <int> <fct> <dbl>
# 1     1 A         5
# 2     2 B         5
# 3     3 C         5
# 4     4 D         5
# 5     5 E         5

The previous R syntax changed the class of our data set from the data frame class to the tbl class. You can see that based on the previously shown RStudio console output.

 

Example 2: Check Whether Data Object is a Tibble with is.tbl Function

Another way how to check whether a data set is a tibble or not is provided by the is.tbl function of the dplyr package. Let’s first apply the is.tbl command to our original data (i.e. the data frame):

is.tbl(my_data)                                 # Check whether data is tibble
# FALSE

Since our input data is not a tibble, the is.tbl function returns FALSE.

Now, let’s apply the is.tbl function to our tibble:

is.tbl(my_tbl)                                  # Check whether data is tibble
# TRUE

As expected: The is.tbl function returns the logical value TRUE.

 

Video & Further Resources

In case you need more info on the R programming code of this tutorial, you might want to watch the following video of my YouTube channel. I illustrate the R programming codes of this tutorial in the video:

 

 

In addition, you may read the other tutorials of my website:

 

To summarize: In this tutorial, I explained how to create a tibble from a data source in the R programming language. Please let me know in the comments section below, in case you have any further questions and/or comments.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top