我正在 R 中创建一个自定义 S3 对象,但是当我打印它时,属性也会被打印。例如:
x <- 1:3
x <- structure(x, class = "myclass")
print(x)
#> [1] 1 2 3
#> attr(,"class")
#> [1] "myclass"
Run Code Online (Sandbox Code Playgroud)
公平地说,我还没有添加print方法。SO 和其他地方的许多答案建议从对象中删除属性,然后打印它,如下所示(也以不可见的方式返回对象以保持原始print属性):
x <- 1:3
x <- structure(x, class = "myclass")
print.myclass <- function(x, ...) {
print(unclass(x), ...)
return(invisible(x))
}
print(x)
#> [1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
然而,这种方法会创建 的副本x,而我不希望这样。我们可以看到tracemem():
x <- 1:3
x <- structure(x, class = "myclass")
tracemem(x)
#> [1] "<0x558e1a9adcc8>"
print.myclass <- function(x, ...) {
print(unclass(x), …Run Code Online (Sandbox Code Playgroud) 我有一个数据框,它用 id 标识一组值:
library(data.table)
dt <- data.table(
id = rep(c("a", "b", "c"), each = 2),
value1 = c(1, 1, 1, 2, 1, 1),
value2 = c(0, 3, 0, 3, 0, 3)
)
dt
#> id value1 value2
#> 1: a 1 0
#> 2: a 1 3
#> 3: b 1 0
#> 4: b 2 3
#> 5: c 1 0
#> 6: c 1 3
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,ida和cidentify 都是同一组值。a因此,我想创建一个“模式 id”,它标识与ids 关联的值集c(obs:一个 id …