Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lapply and subsetting columns

Tags:

r

lapply

subset

xts

I would like the make the bit that uses lapply() more elegant...(i.e. a one liner would be good) rather than having to set up a function before. i.e. is there a standard function in which i can use [,c(1:4)] or something similar as an argument...

so to make a reproducible example...

x <- xts(matrix(rnorm(500*8),ncol=8),Sys.Date()-500:1)
x.m <- split(x,'months')

The following basically only takes the first 4 columns for each element of the list created from the split and thus i have to make a function that does this but i would like it to be more elegant somehow...

ff <- function(xts.obj){xts.obj[,c(1:4)]}

g <- lapply(x.m, ff)

Thanks

like image 417
h.l.m Avatar asked Jul 06 '26 03:07

h.l.m


1 Answers

[ is a function

> args(xts:::`[.xts`)
function (x, i, j, drop = FALSE, which.i = FALSE, ...) 
NULL

So, you can just use that. Either of these will do it.

lapply(x.m, '[', , c(1:4))
lapply(x.m, '[', j=c(1:4))
like image 170
GSee Avatar answered Jul 14 '26 06:07

GSee