【发布时间】:2021-07-19 08:02:18
【问题描述】:
以下几行突出了该问题。属性在许多情况下会转移,但不是在最后一种情况下,这是一个常见的“总结”用例。非常感谢任何帮助!
suppressWarnings(suppressPackageStartupMessages(library(dplyr)))
obj <- c(12, 13, 51)
attributes(obj)<- list(cv = c(3, 4, 2))
print(obj)
#> [1] 12 13 51
#> attr(,"cv")
#> [1] 3 4 2
## 'obj' has an attribute
print(attributes(obj))
#> $cv
#> [1] 3 4 2
tbl <- tibble::tibble(col = obj)
print(tbl$col)
#> [1] 12 13 51
#> attr(,"cv")
#> [1] 3 4 2
## attributes are retained by the col obj was assigned to
print(attributes(tbl$col))
#> $cv
#> [1] 3 4 2
foo <- function(x){
# to be called within 'summarise()'
o <- sum(x)
attributes(o)<- list(cvv = o*2)
return(o)
}
# produces values with attributes
print(foo(7))
#> [1] 7
#> attr(,"cvv")
#> [1] 14
tbl2 <- tbl %>%
summarise(z = foo(col))
# with one single row, attributes are transferred to tbl2
print(attributes(tbl2$z))
#> $cvv
#> [1] 152
tbl2 <- tbl %>%
group_by(col) %>%
summarise(z = foo(col), .groups = "keep")
# with more rows, attributes are NO longer present in tbl2
print(attributes(tbl2$z))
#> NULL
由reprex package (v0.3.0) 于 2021 年 4 月 25 日创建
【问题讨论】:
-
您可以将它们包装在
list即summarise(z = list(foo(col)), .groups = "keep")中,然后检查tbl2$z这是一个listattributes(tbl2$z[[1]])
标签: r dplyr custom-attributes