小编dhe*_*rsz的帖子

如何在 R 中创建不打印属性(不复制对象)的打印方法?

我正在 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)

printing methods copy r

6
推荐指数
1
解决办法
490
查看次数

在 R 中使用 data.table 创建多行组标识符的最快方法是什么?

我有一个数据框,它用 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)

正如您所看到的,idacidentify 都是同一组值。a因此,我想创建一个“模式 id”,它标识与ids 关联的值集c(obs:一个 id …

grouping nested r data.table

5
推荐指数
1
解决办法
192
查看次数

标签 统计

r ×2

copy ×1

data.table ×1

grouping ×1

methods ×1

nested ×1

printing ×1