![](/img/trans.png)
[英]What is the difference between drop.levels(x) in the gdata package and as.factor(as.character(x))?
[英]What is the difference between as.character() and as( ,“character”) in R
在表面上,他們似乎都在做同樣的事情。 但似乎后者as(,"character")
更強大。
舉個例子考慮以下內容:
library(rvest)
temp <- html("http://www.example.com/")
temp <- temp %>% html_node("div p")
str(temp)
#Classes 'XMLInternalElementNode', 'XMLInternalNode', 'XMLAbstractNode' <externalptr>
as.character(temp)
#Error in as.vector(x, "character")
# cannot coerce type 'externalptr' to vector of type 'character'
而as(temp, "character")
給出了
#[1] "<p>This domain is established to be used for illustrative examples in documents. You may use this\n domain in examples without prior coordination or asking for permission.</p>"
as.character()
是S3泛型,而as()
是S4泛型和方法的方法包中定義的函數。
S3類的作者沒有理由編寫S4強制方法,因此對於intance
> as.data.frame(matrix(integer()))
[1] V1
<0 rows> (or 0-length row.names)
但
> as(matrix(integer()), "data.frame")
Error in as(matrix(), "data.frame") :
no method or default for coercing "matrix" to "data.frame"
對於S4類,一個(即包開發者)可以(並且確實應該)編寫用於強制特定類的S3和S4方法; 一個共同的范例是
as.character.MyClass <- function(x, ...) {}
setAs("MyClass", "character",
function(from) as.character.MyClass(from))
在您的示例中,作者(XML)提供了一個沒有S3等效的setAs函數,因此您使用as()
特殊處理,但使用as.character()
時默認(即錯誤as.character()
。
關於哪個“更強大”沒有一般規則; 即使在基礎R和方法包中找到示例也不足為奇,其中as.X和(,“X”)表現不同,甚至以邏輯上不一致的方式。
在R(3.2.0)的下一個版本中,您可以說
> methods(class=class(temp))
[1] [[ coerce html_form html_node html_nodes html_table
[7] initialize show slotsFromS3
see '?methods' for accessing help and source code
其中'coerce'表示存在一個S4方法as(temp, ...")
。實際的方法是
> x = methods(class=class(temp))
There were 18 warnings (use warnings() to see them)
> attr(x, "info")
visible from generic isS4
coerce,oldClass,S3-method TRUE coerce TRUE
coerce,XMLAbstractDocument,XMLAbstractNode-method TRUE XML coerce TRUE
coerce,XMLDocument,XMLInternalDocument-method TRUE XML coerce TRUE
coerce,XMLInternalDocument,character-method TRUE XML coerce TRUE
coerce,XMLInternalDocument,XMLHashTree-method TRUE XML coerce TRUE
coerce,XMLInternalDocument,XMLInternalNode-method TRUE XML coerce TRUE
coerce,XMLInternalNode,XMLInternalDocument-method TRUE XML coerce TRUE
initialize,oldClass-method TRUE initialize TRUE
show,oldClass-method TRUE show TRUE
slotsFromS3,oldClass-method TRUE slotsFromS3 TRUE
另一方面有
> methods(class="matrix")
[1] anyDuplicated as.data.frame as.raster boxplot coerce
[6] determinant duplicated edit head initialize
[11] isSymmetric Math Math2 Ops relist
[16] subset summary tail unique
see '?methods' for accessing help and source code
我們看到方法as.data.frame()
和as.raster()
可用於強制矩陣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.