如果不详细讨论我的具体编程问题,我不太清楚如何提出这个问题。所以,这个问题有点相关,但更简单。我正在尝试理解在分配到S4类的插槽时R应用的过程。我有自定义访问和分配功能," $"和" $< - "。
我注意到两件事:
以下是玩具示例。对第1点的评论和对第2点的回答非常感谢。
setClass("Person"
, representation(FirstName = "character"
, LastName = "character"
, Birthday = "Date")
)
setMethod("$", signature(x = "Person"), function(x, name) {
print("Just called $ accessor")
slot(x, name)
})
setMethod("$<-", signature(x = "Person"), function(x, name, value) {
print("Just called $ assignment")
slot(x, name) = value
x
})
objPeople = new("Person"
, FirstName=c("Ambrose", "Victor", "Jules")
, LastName=c("Bierce", "Hugo", "Verne")
, Birthday=seq(as.Date("2001/01/01"), as.Date("2003/12/31"), by="1 year"))
# This assignment will work. When assigning, there will be a call to the "$" accessor function. Why?
objPeople$FirstName[2] = "Joe"
# This assignment will not make a call to the "$" accessor function. Why?
objPeople$FirstName = "Ambroze"
答案 0 :(得分:4)
请记住,[
只是另一个功能,[<-
也是如此。所以为了做到
objPeople$FirstName[2] = "Joe"
$
将首先运行并返回[<-
可以操作的内容。像
'$<-'(objPeople, "FirstName", '[<-'( '$'(objPeople, "FirstName"), 2, "Joe"))
因此,为了子集,它必须提取名字。但是
objPeople$FirstName = "Ambroze"
那只是一个
'$<-'( objPeople, "FirstName", "Ambroze")
因此您无需致电访问者。你只是直接调用赋值函数。
如果您希望在课程中使用自定义子集,则它将处于Person[]
级别。如果您想在FirstName插槽上使用自定义子集,则必须使FirstName插槽成为其自己的类,您可以在其中重新定义[
方法。