r - 在不破坏 `head` 的情况下扩展 data.table 的 `[` 方法
问题描述
问题:包装[.data.table
似乎禁用了一些打印到控制台的操作,例如head
.
问题:有没有办法修改[.blarg
以便head(b)
打印到控制台?还是我需要编写一个print.blarg
方法或类似的东西?
上下文:我正在尝试轻轻扩展data.table
(请参阅blarg
),以便我可以包装[.data.table
以识别和修改传入的某些对象j
(在 中提供了一个简单的版本[.blarg
。这发生在 R 包开发框架中。我已经包括一个示例head.blarg
函数,但是虽然这似乎在正常环境中工作,但它不能作为包的一部分工作。请参阅帖子底部的代码以尝试包环境。
library('data.table')
blarg <- function(...){
r = data.table::data.table(...)
data.table::setattr(r, 'class', c('blarg', class(r)))
r
}
"[.blarg" <- function(x, i, j, by, ...){
mc <- match.call()
mc[[1]] <- quote(data.table:::`[.data.table`)
res = eval.parent(mc)
}
a = data.table(1:10)
b = blarg(1:10)
#Prints to console
head(a)
#> V1
#> 1: 1
#> 2: 2
#> 3: 3
#> 4: 4
#> 5: 5
#> 6: 6
#Does not print to console-- THIS IS THE PROBLEM BIT
head(b)
#But something is being returned
b1 <- head(b)
print(b1)
#> V1
#> 1: 1
#> 2: 2
#> 3: 3
#> 4: 4
#> 5: 5
#> 6: 6
#' Specifically provide a head definition modeled off of head.data.table
#' @noRd
#' @importFrom utils head
#' @exportS3Method
head.blarg <- function (x, n = 6L, ...)
{
#cat('blarg')
stopifnot(length(n) == 1L)
i = seq_len(if (n < 0L) max(nrow(x) + n, 0L) else min(n,
nrow(x)))
x[i, , ]
}
#This prints to console, but not when as part of a package
head(b)
#> V1
#> 1: 1
#> 2: 2
#> 3: 3
#> 4: 4
#> 5: 5
#> 6: 6
sessionInfo()
#> R version 4.1.1 (2021-08-10)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 19043)
#>
#> Matrix products: default
#>
#> locale:
#> [1] LC_COLLATE=English_United States.1252
#> [2] LC_CTYPE=English_United States.1252
#> [3] LC_MONETARY=English_United States.1252
#> [4] LC_NUMERIC=C
#> [5] LC_TIME=English_United States.1252
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> other attached packages:
#> [1] data.table_1.14.1
#>
#> loaded via a namespace (and not attached):
#> [1] ps_1.6.0 digest_0.6.27 withr_2.4.2 magrittr_2.0.1
#> [5] reprex_2.0.1 evaluate_0.14 highr_0.9 stringi_1.6.1
#> [9] rlang_0.4.11 cli_2.5.0 rstudioapi_0.13 fs_1.5.0
#> [13] rmarkdown_2.8 tools_4.1.1 stringr_1.4.0 glue_1.4.2
#> [17] xfun_0.23 yaml_2.2.1 compiler_4.1.1 htmltools_0.5.1.1
#> [21] knitr_1.33
作为软件包的一部分:
devtools::install_github('dcaseykc/headdtest')
source('https://raw.githubusercontent.com/dcaseykc/headdtest/main/exmple.R')
head(a) # Will print to console
head(b) # Probably won't print to console
解决方案
经过更多测试后,更改[.blarg
为显式返回res
似乎有效。
"[.blarg" <- function(x, i, j, by, ...){
mc <- match.call()
mc[[1]] <- quote(data.table:::`[.data.table`)
res = eval.parent(mc)
return(res)
}
推荐阅读
- php - Gmail CC(复制)之类的实施
- angular - 等到完成 setTimeout
- google-cloud-platform - 当 Google Cloud Platform 计算引擎实例中的本地 SSD 发生故障时会发生什么?
- python-3.x - 零填充元组(范围(1,31))
- flutter - Flutter 提供商不允许我访问数据
- python - 使用 argparse 错误地传递参数
- python - 包围图像的所有黑色像素的最小角度矩形
- python - 如何在matplotlb中的alpha区域后面画一条线?
- php - 如何匹配/配对两个数组元素并在 PHP 中只返回一个
- mysql - 我正在尝试使用此查询创建一个 VIEW 但不起作用