R语言 获取对象的属性 – attributes()和attr()函数
R编程语言中的 attribute() 函数用于获取数据的所有属性。这个函数也被用来为数据设置新的属性。
语法: attributes(x)
参数
- x: 要访问其属性的对象。
R语言 获取对象的属性
例子 1: 实现 attributes() 函数
# R program to illustrate
# attributes function
info = data.frame(iris)
# Load info set that you want to work on
data(info)
# Print first 6 rows of info set data
head(info)
# Apply attributes function
attributes(info)
输出
在上面的代码中,我们应用了attributes()函数,所以我们显示了所有存在于info数据框中的数据。因此,通过应用info,数据集中的所有属性都将被显示出来。
例2:在R语言中为属性分配新值
# Set different column names
# retain dataframe class
attributes_list <- list(names = c('Sepal.Length' ,'Sepal.Width' ,
'Petal.Length', 'Petal.Width',
'Species'),
class = "data.frame",
row.names= c("NA","NA","NA","NA"))
# New attributes from list added to info database
attributes(info) <- attributes_list
attributes(info)
输出
$names
'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species'
$class
'data.frame'
$row.names
'NA' 'NA' 'NA' 'NA'
在上面的代码中,我们将新的属性添加到例1的列表信息中,然后打印了包括新属性在内的所有属性。
attr() 函数
attr() 将返回特定的数据,但这个函数需要关于数据的精确信息。
语法:
attr(x = data, which = “attribute_name”)
参数
- x: 要访问其属性的对象。
- which: 指定要访问的属性的字符串。
例子。实现attr()函数
# R program to illustrate
# attr() function
# Load info set that you want to work on
data(info)
# Apply attr() function
attr(x = info, which = "names")
输出
'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species'
在上面的代码中,我们指定了一个特定的参数名称,所以只有名称中的值会被返回。attr()会返回特定的数据,但是attr()函数需要一个关于数据的精确信息。