[R] Making an S3 object act like a data.frame
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Mar 7 22:27:19 CET 2006
If your class is a subclass of data.frame then I think
it ought to be a special sort of data frame so all you
need to do is the following in which case you get subscripting
for free by inheritance:
# constructor
myobj <- function(...)
structure(data.frame(...), class = c("myobj", "data.frame"))
# test
x <- myobj(x = 1:3, y = 4:6)
class(x)
x[[1]]
x$x
On 3/7/06, hadley wickham <h.wickham at gmail.com> wrote:
> "[.ggobiDataset" <- function(x, ..., drop=FALSE) {
> x <- as.data.frame(x)
> NextMethod("[", x)
> }
>
> "[[.ggobiDataset" <- function(x, ..., drop=FALSE) {
> x <- as.data.frame(x)
> NextMethod("[[", x)
> }
>
> "$.ggobiDataset" <- function(x, ..., drop=FALSE) {
> x <- as.data.frame(x)
> NextMethod("$", x)
> }
>
> > class(x)
> [1] "ggobiDataset" "data.frame"
>
> > x[1:2,1:2]
> total_bill tip
> 1 16.99 1.01
> 2 10.34 1.66
>
> > x[[1]]
> [1] 16.99 10.34 21.01 23.68 24.59 25.29 8.77 26.88 15.04 14.78 10.27 35.26
> [13] 15.42 18.43 14.83 21.58 10.33 16.29 16.97 20.65 17.92 20.29 15.77 39.42
> ...
>
> > x$total_bill
> Error in "$.default"(x, "total_bill") : invalid subscript type
>
>
> What do I need to do to get "$.ggobiDataset" to imitate a data.frame
> like [ and [[ do?
>
> Thanks,
>
> Hadley
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
More information about the R-help
mailing list