The detach() function removes a database or object library/package from the search path. It can also detach objects combined by attach() like DataFrame, series, and so on.
detach(name,pos = 2L,unload = FALSE,character.only = FALSE,force = FALSE)
name: The DataFrame object to be detached. It can either be a number or a character string when character.only is set to TRUE. pos: This is the position in the database or index.unload: This is used to check whether namespaces can be unloaded or not. character.only: This is a logical value.FALSEname as a character string, when character.only is set to TRUE.force: This is a logical value.FALSE means not removing forcefully.TRUE, it will forcefully remove packages even when other objects are dependent.In this code snippet, we'll use a generic function .tbl to convert a DataFrame into a table. This function belongs to the dplyr library and can be attached to detached by using attach() or detach() functions.
# R program to illustrate detach function# Using dplyr packagelibrary(dplyr, warn.conflicts = FALSE) # attach dplyr# Creating a DataFramedf= data.frame(x=c(2,3,4,5,7,4),y=c(1.1,2.1,4.5,45.1,3.2,66),z=c(TRUE,FALSE,TRUE,TRUE,FALSE,FALSE))# Apply as.tbl function of dplyr packagedf_tbl <- as.tbl(df)print(df_tbl)# Detaching dplyr packagedetach("package:dplyr", unload = FALSE)# Creating another DataFramedf= data.frame(x=c(2,3,4,5,7,4),y=c(TRUE,FALSE,TRUE,TRUE,FALSE,FALSE))# Apply as.tbl after detaching dplyr packagedata_tbl <- as.tbl(df)
Note: It will show aas.tbl(df) : could not find function "as.tbl"error.
dplyr package in the program.as.tbl() from the dplyr package to convert DataFrame into a table. We print it to the console.detach() function to detach the dplyr package from the current program.as.tbl() from dplyr package after detaching. Hence, it will show an error. To ensure whether the code is working correctly or not, we can simply comment the detach() and it won't give any errors.