Skip to content
Prev 300324 / 398503 Next

subsetting without losing the attributes

Hi,

How do I use the subset function without losing the attributes?

For example,

test.df <- data.frame(a = rnorm(100), b = runif(100), c = rexp(100))
attr(test.df[, 1], "units") <- c("cm")
attr(test.df[, 2], "units") <- c("kg")
attr(test.df[, 3], "units") <- c("ha")


## We want this behavior
str(test.df[, "a", drop = FALSE])

## But not the behavior of subset
str(subset(test.df, select = a, drop = FALSE))
## Whic is equivalent to
str(test.df[TRUE, "a", drop = FALSE])

Cheers,
M