我定義了一個類(tdtfile
),它繼承data.frame
。我現在試圖定義一個[.data.frame
等效替換方法來返回類tdtfile
而不是data.frame
的適當對象,但遇到問題。自定義類繼承`data.frame`和替換方法
下面是我在做什麼:
# Define Class
setClass("tdtfile",
representation(Comment = "character"),
prototype(Comment = NULL),
contains = c("data.frame"))
# Construct instance and populate
test <- new("tdtfile",Comment="Blabla")
df <- data.frame(A=seq(26),B=LETTERS)
for(sName in names(getSlots("data.frame"))){
slot(test,sName) <- slot(df,sName)
}
# "Normal" data.frame behavior (loss of slot "Comment")
str(test[1])
# Works as well - will be trying to use that below
`[.data.frame`(test,1)
# Try to change replacement method in order to preserve slot structure
# while accessing data.frame functionality
setMethod(
`[`,
signature=signature(x="tdtfile"),
function(x, ...){
# Save the original
storedtdt <- x
# Use the fact that x is a subclass to "data.frame"
tmpDF <- `[.data.frame`(x, ...)
# Reintegrate the results
if(inherits(x=tmpDF,what="data.frame")){
for(sName in names(getSlots("data.frame"))){
slot(storedtdt,sName) <- slot(tmpDF,sName)
}
return(storedtdt)
} else {
return(tmpDF)
}
})
# Method does not work - data.frame remains complete. WHY?
str(test[1])
# Cleanup
#removeMethod(
# `[`,
# signature=signature(x="tdtfile"))
當調用類似
tdtfile[1]
這將返回AA tdtfile
物體都含有相當data.frame
列不僅僅是第一...誰能發現我錯過了什麼?
謝謝你的幫助。
真誠,荷蘭Joh
嗨Joh,歡迎來到SO。你能否詳細說明你的最後一句話。你具體看到什麼,你想看到什麼? – 2013-02-24 08:29:49
感謝您關注此事。我大大改進了這個例子,使其完全獨立/可重複。我正在嘗試做什麼,現在看得清楚(呃)? – balin 2013-02-25 05:40:39