有效的代码:duration
和period
对象
下面的代码分别成功生成了一个duration
对象和一个period
对象。
> lubridate::as.duration(1)
[1] "1s"
> lubridate::seconds(1)
[1] "1S"
不起作用的代码:duration
以及speriod
中的对象tibble
但是,当我尝试使用 a或对象创建tibble
s时,我会收到无意义的错误消息。duration
period
> tibble::tibble(y = lubridate::as.duration(1))
Error: Incompatible duration classes (Duration, numeric). Please coerce with `as.duration`.
> tibble::tibble(y = lubridate::seconds(1))
Error in x < 0 : cannot compare Period to Duration:
coerce with 'as.numeric' first.
有效的代码:s中duration
的period
对象data.frame
tibble::tibble
以base::data.frame
作品代替。
> data.frame(y = lubridate::as.duration(1))
y
1 1s
> data.frame(y = lubridate::seconds(1))
y
1 1S
不起作用的代码 - 强制这些data.frame
stibbles
使用tibble::as_tibble
强制这些data.frame
stibbles
产生与以前相同的错误。
> tibble::as_tibble(data.frame(y = lubridate::as.duration(1)))
Error: Incompatible duration classes (Duration, numeric). Please coerce with `as.duration`.
> tibble::as_tibble(data.frame(y = lubridate::seconds(1)))
Error in x < 0 : cannot compare Period to Duration:
coerce with 'as.numeric' first.
可能的解释
Hadley 在这个 Github 问题中提到了一些东西 - https://github.com/tidyverse/tibble/issues/326 - 关于 S4 列,其中包括as.duration
和as.period
. 没有特别提到不兼容。
挖掘源代码,我发现以下依赖链给出了相同的错误消息:as_tibble.data.frame --> list_to_tibble --> new_tibble
在tibble:::list_to_tibble
中,传递给的唯一参数tibble::new_tibble
是x
。因此,subclass
被赋予默认值NULL
, 的倒数第二行tibble::new_tibble
变为
class(x) <- c("tbl_df", "tbl", "data.frame")
对象具有结构,但尝试直接调用它们会产生错误。
> x <- data.frame(y = lubridate::as.duration(1))
> class(x) <- c("tbl_df", "tbl", "data.frame")
> str(x)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 1 obs. of 1 variable:
$ x:Formal class 'Duration' [package "lubridate"] with 1 slot
.. ..@ .Data: num 1
> x
Error: Incompatible duration classes (Duration, numeric). Please coerce with `as.duration`.
> x <- data.frame(y = lubridate::seconds(1))
> class(x) <- c("tbl_df", "tbl", "data.frame")
> str(x)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 1 obs. of 1 variable:
$ y:Formal class 'Period' [package "lubridate"] with 6 slots
.. ..@ .Data : num 1
.. ..@ year : num 0
.. ..@ month : num 0
.. ..@ day : num 0
.. ..@ hour : num 0
.. ..@ minute: num 0
> x
Error in x < 0 : cannot compare Period to Duration:
coerce with 'as.numeric' first.
因此,似乎分配data.frame
x
向量的类c("tbl_df", "tbl", "data.frame")
会导致R
尝试以x
引发错误的方式强制。
此外,鉴于tibble::tibble
也调用as_tibble
(尽管不是在 a 上data.frame
),我会冒险猜测我的问题tibble::tibble
具有相同的原因。
软件包版本
- 小标题:1.4.1
- 润滑:1.7.1
- R:3.4.3