Nicolás Vargas Nicolás Vargas - 5 months ago 29
R Question

Use lapply to modify the data of an xts contained on a list

I am trying to change the first data of all the xts I have contained within a list but I can't seem to figure out how the syntax would be for

to do this. I have tried with:

b = lapply(a, function(a) a[1,]=1)

But this erases all the other rows' data. Does anyone knows the right syntax to address to the first data and modify it.


Answer Source

Your internal function returning the a[1,]=1 as a result, therefore you didn't have the whole xts stored.

Use like this:

b <- lapply(a, function(a) { a[1,] = 1; a })

Another way is to use [<- (anonymous assignment):

b <- lapply(a, `[<-`, 1, TRUE, 1)


sample.xts <- as.xts(sample_matrix, descr='my new xts object')

a <- rep(list(sample.xts), 2000)

microbenchmark(assign = lapply(a, function(a) { a[1,] = 1; a }),
               anon_assign = lapply(a, `[<-`, 1, TRUE, 3))

Unit: milliseconds
        expr      min       lq     mean   median       uq       max neval
      assign 33.50660 39.90533 58.75338 43.74316 88.39256 128.15991   100
 anon_assign 29.95665 32.37879 44.80245 34.11000 38.87301  97.35795   100

Therefore, the anonymous assign version is much faster.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download