在R编程中访问数据框的变量 – attach()和detach()函数
在这篇文章中,我们将看到如何在R编程语言中访问数据框的变量。
R – 访问数据框的变量
方法1:使用R语言中的attach()函数
R语言 中的attach()函数 **** ,用于访问数据框架中的变量,而无需调用数据框架。
语法: attach(data, pos)
参数 。
- data: 数据框架
- pos: 数据库的位置
例子。使用attach()函数在R中访问数据框的变量
# R program to illustrate
# attach function
# Create example data
data <- data.frame(x1 = c(1, 2, 3, 4, 5),
x2 = c(6, 7, 8, 9, 0),
x3 = c(1, 2, 5, 4, 5))
# Try to print x1
# Error: object 'x1' not found
# attach data
attach(data, pos = x1)
输出 。
1 2 3 4 5
在上面的代码中,我们创建了一个数据框架,并给它分配了一个值,当我们试图返回值时,发生了错误。然后我们使用attach函数并返回x1的值。
方法2:使用detach()函数
detach() 函数用于移除由attach()函数生成的数据框架中的附件。
语法: detach(data, unload)
参数。
- data: 数据框架
- unload: 布尔值
例子。使用detach()函数在R中访问数据框的变量
# R program to illustrate
# detach function
# Install dplyr package
install.packages("dplyr")
# attach dplyr
library("dplyr")
# Apply as.tbl function of dplyr package
data_tbl <- as.tbl(data)
detach("package:dplyr", unload = FALSE)
# Apply as.tbl after detaching dplyr package
data_tbl <- as.tbl(data)
输出 。
Error in as.tbl(data) : could not find function “as.tbl”
在上面的代码中,我们安装了一个dplyr包并使用了它的函数as.tbl。然后我们分离了这个包,并试图再次使用这个函数,结果出现了错误。分离函数是用来解压被添加到库中的库的。