[R] losing variable attributes when subsetting model.frame
Vito Muggeo
v|to@muggeo @end|ng |rom un|p@@|t
Wed May 8 14:57:54 CEST 2024
dear Duncan,
Thank you very much for your quick reply. Very useful and also very
elegant, I would add.
Thanks again,
kind regards,
Vito
Il 08/05/2024 14:06, Duncan Murdoch ha scritto:
> I would guess that subsetting uses [] indexing on each column, with a
> logical argument. If that is true, then one solution (which is less
> direct, but maybe someone would call it elegant) is to put a class on
> the result of `f()`, and define a `[` method for that class that
> preserves the attributes you want to preserve.
>
> In your example:
>
> f <- function(x) {
> attr(x, "vi") <- length(x)
> class(x) <- c("withAttributes", class(x))
> x
> }
>
> `[.withAttributes` <- function(x, i) {
> subset <- NextMethod()
> attr(subset, "vi") <- attr(x, "vi")
> subset
> }
>
>
> x<- 1:5
> z<-runif(5)
> y<-rnorm(5)
>
> mf <- model.frame(y~f(z), subset=x>=3)
> attr(mf[,2],"vi") #it works
> #> [1] 5
--
=================================================
Vito M.R. Muggeo, PhD
Professor of Statistics
Dip.to Sc Econom, Az e Statistiche
Università di Palermo
viale delle Scienze, edificio 13
90128 Palermo - ITALY
tel: 091 23895240; fax: 091 485726
http://www.unipa.it/persone/docenti/m/vito.muggeo
Assoc Editor: Statist Modelling, Statist Meth Appl
past chair, Statistical Modelling Society
coordinator, PhD Program in Econ, Businss, Statist
More information about the R-help
mailing list