在 'summarise(data, lhs = rhs)' 调用中:有没有办法将 rhs 的属性传递给 lhs?

问题描述

以下几行突出显示了该问题。属性在许多情况下会被转移,但不是在最后一种情况下,这是一个常见的“总结”用例。非常感谢任何帮助!

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 日创建

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)