0

我目前正在研究 S3 类,试图为我的类生成一个写入函数。只是一个最小的例子:

testclass <- function() {
    value  <- list(c(1,2))
    attr(value, "class") <- "testclass"
    value
}
print.testclass <- function(obj) {
    cat("testtest")
}
summary.testclass <- function(obj) {
    cat("testtest2")
}
write.testclass <- function(obj) {
    cat("testtest3")
}


##### Testing:
> a <- testclass()
> print(a)
testtest
> a
testtest
> summary(a)
testtest2
> write(a)
Error in file(file, ifelse(append, "a", "w")) : 
    cannot open the connection
In addition: Warning message:
    In file(file, ifelse(append, "a", "w")) :
    cannot open file 'data': Permission denied

那么,为什么写不使用正确的写呢?

解决方案:

write <- function(x, ...) UseMethod("write")
write.default <- base::write
write.testclass <- function(obj) {
    cat("testtest3")
}

> write(a)
testtest3
4

0 回答 0