请考虑以下列表:
lst <- list(
a = structure("x", class = "foo", type = "bar"),
b = "y"
)
str(lst)
#> List of 2
#> $ a: 'foo' chr "x"
#> ..- attr(*, "type")= chr "bar"
#> $ b: chr "y"
创建于2024-03-01年第reprex v2.1.0页
当用另一个值替换类foo
的元素时,我希望保留这些属性.
基本上,我希望有一种方法可以复制以下行为:
res <- (function(x, i, value) {
attrs <- attributes(x[[i]])
x[[i]] <- value
attributes(x[[i]]) <- attrs
x
})(lst, "a", "z")
str(res)
#> List of 2
#> $ a: 'foo' chr "z"
#> ..- attr(*, "type")= chr "bar"
#> $ b: chr "y"
创建于2024-03-01年第reprex v2.1.0页
我怎么能做到这一点?我想解决方案是实现一个`[[<-.foo`
方法,但不知道如何使其工作?据我所知,这种方法将使用lst
的类,而不是它所包含的元素的类.
我只想找一个基础的R解决方案.