Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R apply functional that keeps attributes

How can I keep the attributes (class etc.) of an object after applying a vector functional from R, such as sapply or vapply?

> d <- c(as.POSIXct(Sys.time()), as.POSIXct(Sys.time()) + 60)
> typeof(d)
[1] "double"
> class(d)
[1] "POSIXct" "POSIXt"

> sapply(d, function(x) x)
[1] 1510760756 1510760816
> vapply(d, function(x) x, double(1))
[1] 1510760756 1510760816

I could circumvent this problem with

> do.call(c, as.list(d))
[1] "2017-11-15 16:45:56 CET" "2017-11-15 16:46:56 CET"

but then I have to build a list first.

Thank you!

like image 849
lkegel Avatar asked Apr 30 '26 19:04

lkegel


1 Answers

sapply has a default argument simplify = TRUE which forces the output to be a vector, matrix, or higher-dimensional array. If you change it to FALSE:

> sapply(d, function(x) x, simplify = FALSE)
[[1]]
[1] "2018-02-21 12:43:52 CET"

[[2]]
[1] "2018-02-21 12:44:52 CET" 

you get a list.

Note that this would be the same result you would get from lapply(d, function(x) x).

But if you don't want a list at the end, Grothendieck's comment seems the cleanest way to me. You can wrap it inside a higher-order function if you want it slightly cleaner:

> m.sapply <- function(x, ...) "attributes<-"(sapply(x, ...), attributes(x))

> m.sapply(d, function(x) x)
[1] "2018-02-21 12:43:52 CET" "2018-02-21 12:44:52 CET"
like image 104
koohyar Avatar answered May 02 '26 10:05

koohyar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!