UPDATE: As of haven版本2.0.0 https://github.com/tidyverse/haven/blob/master/NEWS.md#haven-200这个问题已经解决,因为避难所“labelled”类被重命名为"haven_labelled"
以避免与Hmisc.
tl;dr:顺序很重要。
为了获得更详细的答案,我们首先重现该错误:
library(Hmisc)
#> Loading required package: lattice
#> Loading required package: survival
#> Loading required package: Formula
#> Loading required package: ggplot2
#>
#> Attaching package: 'Hmisc'
#> The following objects are masked from 'package:base':
#>
#> format.pval, units
library(tidyverse)
#> Warning: package 'forcats' was built under R version 3.4.4
从原始内容中逐段删除元素后summarise
例子,
我设法将错误重现减少为以下代码行:
Hmisc::label(iris$Petal.Width) <- "Petal Width"
head(iris)
#> Error: `x` and `labels` must be same type
我们可以查看回溯,看看是否可以找到可能导致错误的函数:
traceback()
#> 8: stop("`x` and `labels` must be same type", call. = FALSE)
#> 7: labelled(NextMethod(), attr(x, "labels"))
#> 6: `[.labelled`(xj, i)
#> 5: xj[i]
#> 4: `[.data.frame`(x, seq_len(n), , drop = FALSE)
#> 3: x[seq_len(n), , drop = FALSE]
#> 2: head.data.frame(iris)
#> 1: head(iris)
The [.labelled
电话看起来很可疑。为什么它甚至被称为?
lapply(iris, class)
#> $Sepal.Length
#> [1] "numeric"
#>
#> $Sepal.Width
#> [1] "numeric"
#>
#> $Petal.Length
#> [1] "numeric"
#>
#> $Petal.Width
#> [1] "labelled" "numeric"
#>
#> $Species
#> [1] "factor"
啊,设置标签Petal.Width
with Hmisc::label
还添加了S3类。
我们可以检查该方法的定义位置getAnywhere
:
getAnywhere("[.labelled")
#> 2 differing objects matching '[.labelled' were found
#> in the following places
#> registered S3 method for [ from namespace haven
#> namespace:Hmisc
#> namespace:haven
#> Use [] to view one of them
确实,两者haven
and Hmisc
定义方法。自从haven
是
之后加载Hmisc
,它的定义首先被找到,因此被使用:
getAnywhere("[.labelled")[1]
#> function (x, ...)
#> {
#> labelled(NextMethod(), attr(x, "labels"))
#> }
#> <environment: namespace:haven>
haven
期望labelled
对象有一个labels
属性,其中Hmisc::label
不创建:
attr(iris$Petal.Width, "labels")
#> NULL
这就是错误的来源。
But wait: why is
haven
even loaded? It's not attached with
library(tidyverse)
.
Turns out, that
haven
is
listed as an imported package https://github.com/tidyverse/tidyverse/blob/master/DESCRIPTION in
tidyverse
,
which causes it to be loaded when the package is attached (see e.g.
here http://r-pkgs.had.co.nz/namespace.html). And loading a package,
among other things, registers its S3 methods: which is where the conflict
comes from.
事实上,如果您想同时使用两者Hmisc
and tidyverse
,顺序很重要。
要进一步解决该问题可能需要更改源级别
包的使用labelled
S3级。
创建于 2018-03-21代表包 http://reprex.tidyverse.org(v0.2.0)。