【发布时间】:2020-03-09 10:15:30
【问题描述】:
我想有几种方法可以做到这一点。因此,这个问题的答案 可能是主观的,如果不是自以为是的话。所以我会尝试缩小问题的范围,并且 告诉你我已经做过的细节。
上下文
我正在使用R6 包,我创建了一个IntervalNumeric
R6Class 有两个字段lower_bound 和upper_bound:
require(R6)
NumericInterval <-
R6Class(
"NumericInterval",
public = list(
lower_bound = NA,
upper_bound = NA,
initialize = function(low, up) {
self$lower_bound <- low
self$upper_bound <- up
},
as_character = function() {
paste0("[", self$lower_bound, ", ",
self$upper_bound, "]")}))
我还使用S3 泛型方法系统来获得as.character 和printfor
NumericInterval 类型:
as.character.NumericInterval <- function(x, ...) {
x$as_character()}
print.NumericInterval <- function(x, ...) {
x$as_character()}
现在我可以做到这一点(print 也是如此):
> as.character(NumericInterval$new(0, pi))
[1] "[0, 3.14159265358979]"
问题:
现在需要做什么才能将此新类型用作data.frame 列类型?
例如我希望能够做到这一点:
(df <- data.frame(
X = c("I1", "I2", "I3"),
Y = c(NumericInterval$new(0,1),
NumericInterval$new(1,2),
NumericInterval$new(2,3)))
然后得到:
X Y
1 I1 [0, 1]
2 I2 [1, 2]
3 I3 [2, 3]
但我明白了:
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class ‘c("NumericInterval", "R6")’ to a data.frame
当然,我也希望能够访问对象并执行以下操作:
df[2, 2]$lower_bound <- 0
tibbles 似乎是一个解决方案
(df <- tibble(
X = c("I1", "I2", "I3"),
Y = c(NumericInterval$new(0,1),
NumericInterval$new(1,2),
NumericInterval$new(2,3))))
产生:
# A tibble: 3 x 2
X Y
<chr> <list>
1 I1 <NmrcIntr>
2 I2 <NmrcIntr>
3 I3 <NmrcIntr>
每个NumericInterval 都按预期放置,例如:
> require(dplyr)
> df[2,1][[1]] %>% pull
[[1]]
<NumericInterval>
Public:
as_character: function ()
clone: function (deep = FALSE)
initialize: function (low, up)
lower_bound: 0
upper_bound: 1
但是tibble的输出和访问对象的方式不是我的 期待。
【问题讨论】:
-
我不是这方面的专家,但是您是否为您的新课程定义了
print()方法? -
好的,我已经添加了一个
print(),它现在没有任何改变。但也许这是个好主意。
标签: r dataframe types tibble r6