[R] Retaining attributes of columns of a data frame when subsetting.

Richard M. Heiberger rmh @end|ng |rom temp|e@edu
Sun Oct 20 04:00:51 CEST 2019


Look at
methods(as.data.frame)
Define your specialized columns to have a newly defined class, say "myclass".
Then write as.data.frame.myclass
It will be similar to the function you already have in the lapply statement.
Now your statement
X <- X[ok,]
should work.

Rich

On Sat, Oct 19, 2019 at 8:20 PM Rolf Turner <r.turner using auckland.ac.nz> wrote:
>
>
> I am writing a function that involves a data frame "X" some columns of
> which have attributes.  I replace X by a data frame with a subset of the
> rows of X:
>
>      X <- X[ok,]
>
> where "ok" is a logical vector.  When I do this the attributes of the
> columns (which I need to retain) are lost (except for the "class" and
> "levels" attributes of columns which are factors).
>
> Is there any sexy way to retain the attributes of the columns?
>
> So far the only approach that I can work out is to extract the
> attributes prior to subsetting and put them back after subsetting.
>
> Like unto:
>
>      SaveAt <- lapply(X,attributes)
>      X <- X[ok,]
>      lX <- lapply(names(X),function(nm,x,Sat){
>                                 attributes(x[[nm]]) <- Sat[[nm]]
>                                 x[[nm]]},x=X,Sat=SaveAt)
>      names(lX) <- names(X)
>      X <- as.data.frame(lX)
>
> This seems to work, but is rather kludgy.  Is there a better way?
>
> Thanks for any pointers.
>
> cheers,
>
> Rolf Turner
>
> --
> Honorary Research Fellow
> Department of Statistics
> University of Auckland
> Phone: +64-9-373-7599 ext. 88276
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list