[R] Retaining attributes of columns of a data frame when subsetting.
Rui Barradas
ru|pb@rr@d@@ @end|ng |rom @@po@pt
Sun Oct 20 14:15:57 CEST 2019
Hello,
Richard's idea is good but shouldn't it be `[.myclass` instead?
`[.myclass` <- function(x, i, j, drop = if (missing(i)) TRUE else
length(cols) == 1){
SaveAt <- lapply(X, attributes)
X <- NextMethod()
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)
X
}
X <- data.frame(a = letters[1:5], x = 1:5)
class(X) <- c("myclass", class(X))
attr(X$a, "attr_a1") <- "first_a"
attr(X$a, "attr_a2") <- "second_a"
str(X)
ok <- c(1, 3, 4)
X <- X[ok, ]
str(X)
Hope this helps,
Rui Barradas
Às 03:13 de 20/10/19, Rolf Turner escreveu:
> On 20/10/19 3:00 PM, Richard M. Heiberger wrote:
>> 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.
>
> Yes. That idea does indeed look promising. I'll check it out.
> Thanks.
>
> cheers,
>
> Rolf
>
More information about the R-help
mailing list