我试图了解如何用向量构建对象。我认为这很简单,但是当我在我的对象上使用 c() 时遇到了麻烦。
我们的对象有两个属性,x 和描述符,在本例中都是字符串(我的对象将具有不同类型的属性)。我们构建了一个构造函数 new_toy_vector。我还没有在这个例子中构建一个便利的函数。
new_toy_vector <- function(
x = character(),
descriptor = character()) {
vctrs::vec_assert(x,character())
vctrs::vec_assert(descriptor, character())
vctrs::new_vctr(x,
descriptor = descriptor,
class = "toy_vector")
}
format.toy_vector <- function(x, ...) {
paste0(vctrs::vec_data(x)," is ", attr(x, "descriptor"))
}
obj_print_data.toy_vector <- function(x) {
cat(format(x), sep = "\n")
}
c(new_toy_vector("Hello", "Foo"), new_toy_vector("World", "Bar"))
#> Error: No common type for `..1` <toy_vector> and `..2` <toy_vector>.
Created on 2020-04-26 by the reprex package https://reprex.tidyverse.org (v0.3.0)
然后,我尝试对其自身创建强制转换,除非由于某种原因未定义默认方法:
> vec_ptype2.toy_vector.toy_vector <- function(x, y, ...) new_toy_vector()
> c(new_toy_vector("Hello", "Foo"), new_toy_vector("World", "Bar"))
Error: Can't convert <toy_vector> to <toy_vector>.
我有什么遗漏或误解的想法吗?为什么我不能合并示例中的两个对象?