当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R purrr attr_getter 创建属性 getter 函数


attr_getter() 生成属性访问器函数;即,它生成一个用于提取具有给定名称的属性的函数。与具有默认选项的基本 R attr() 函数不同,它不使用部分匹配。

用法

attr_getter(attr)

参数

attr

字符串形式的属性名称。

也可以看看

例子

# attr_getter() takes an attribute name and returns a function to
# access the attribute:
get_rownames <- attr_getter("row.names")
get_rownames(mtcars)
#>  [1] "Mazda RX4"           "Mazda RX4 Wag"       "Datsun 710"         
#>  [4] "Hornet 4 Drive"      "Hornet Sportabout"   "Valiant"            
#>  [7] "Duster 360"          "Merc 240D"           "Merc 230"           
#> [10] "Merc 280"            "Merc 280C"           "Merc 450SE"         
#> [13] "Merc 450SL"          "Merc 450SLC"         "Cadillac Fleetwood" 
#> [16] "Lincoln Continental" "Chrysler Imperial"   "Fiat 128"           
#> [19] "Honda Civic"         "Toyota Corolla"      "Toyota Corona"      
#> [22] "Dodge Challenger"    "AMC Javelin"         "Camaro Z28"         
#> [25] "Pontiac Firebird"    "Fiat X1-9"           "Porsche 914-2"      
#> [28] "Lotus Europa"        "Ford Pantera L"      "Ferrari Dino"       
#> [31] "Maserati Bora"       "Volvo 142E"         

# These getter functions are handy in conjunction with pluck() for
# extracting deeply into a data structure. Here we'll first
# extract by position, then by attribute:
obj1 <- structure("obj", obj_attr = "foo")
obj2 <- structure("obj", obj_attr = "bar")
x <- list(obj1, obj2)

pluck(x, 1, attr_getter("obj_attr"))  # From first object
#> [1] "foo"
pluck(x, 2, attr_getter("obj_attr"))  # From second object
#> [1] "bar"
源代码:R/pluck.R

相关用法


注:本文由纯净天空筛选整理自Hadley Wickham等大神的英文原创作品 Create an attribute getter function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。