What is the detach() function in R?
Overview
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.
Syntax
detach(name,pos = 2L,unload = FALSE,character.only = FALSE,force = FALSE)
Parameters
name: The DataFrame object to be detached. It can either be a number or a character string whencharacter.onlyis set toTRUE.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.- Default =
FALSE - Set
nameas a character string, whencharacter.onlyis set toTRUE. force: This is a logical value.- Default =
FALSEmeans not removing forcefully. - When set to
TRUE, it will forcefully remove packages even when other objects are dependent.
Example
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.
Explanation
- Line 3: We include the
dplyrpackage in the program.
- Lines 5–7: We create a DataFrame of six
and threerows Observations .columns Features - Lines 9–10: We use
as.tbl()from thedplyrpackage to convert DataFrame into a table. We print it to the console. - Line 12: We call the
detach()function to detach thedplyrpackage from the current program. - Lines 14–17: We call
as.tbl()fromdplyrpackage after detaching. Hence, it will show an error. To ensure whether the code is working correctly or not, we can simply comment thedetach()and it won't give any errors.