简体   繁体   中英

Subset and lagging list data structure

I have a list that is indexed like the following:

>list.stuff
[[1]]
[[1]]$vector
...
[[1]]$matrix
....
[[1]]$vector

[[2]]
null

[[3]]
[[3]]$vector
...
[[3]]$matrix
....
[[3]]$vector
.
.
.

Each segment in the list is indexed according to another vector of indexes:

>index.list
1, 3, 5, 10, 15

In list.stuff , only at each of the indexes 1,3,5,10,15 will there be 2 vectors and one matrix; everything else will be null like [[2]] . What I want to do is to lag like the lag.xts function so that whatever is stored in [[1]] will be pushed to [[3]] and the last one drops off. This also requires subsetting the list, if its possible. I was wondering if there exists some functions that handle list manipulation.

My thinking is that for xts , a time series can be extracted based on an index you supply:

xts.object[index,]  #returns the rows 1,3,5,10,15

From here I can lag it with:

lag.xts(xts.object[index,])

Any help would be appreciated thanks:

EDIT: Here is a reproducible example:

list.stuff<-list()
vec<-c(1,2,3,4,5,6,7,8,9)
vec2<-c(1,2,3,4,5,6,7,8,9)
mat<-matrix(c(1,2,3,4,5,6,7,8),4,2)

list.vec.mat<-list(vec=vec,mat=mat,vec2=vec2)


ind<-c(2,4,6,8,10)
for(i in ind){
   list.stuff[[i]]<-list.vec.mat
}

slist<-list.stuff[ind]
list.stuff[ind]<-lapply(seq_along(slist),function(i) ifelse(i <= 1, NA, slist[[i-1]])) #lag list

The new lagged list only preserves one of the vectors rather than 2 vectors and list

First, an example list:

elist <- list(1, 2, 3, 4, 5, 6)

The index:

index.list <- c(1, 3, 5)

Create a subset based on the index:

sublist <- elist[index.list]

[[1]]
[1] 1

[[2]]
[1] 3

[[3]]
[1] 5

The lag:

lag <- 1

Apply a lag of size lag to the list

newsublist <- lapply(seq_along(sublist),
                     function(i) if (i <= 1) NA else slist[[i-1]])

[[1]]
[1] NA

[[2]]
[1] 1

[[3]]
[1] 3

Note . In its current implementation, the last command works for positive lags only.

Now, put the values back into the list elist :

elist[index.list] <- newsublist

The result:

[[1]]
[1] NA

[[2]]
[1] 2

[[3]]
[1] 1

[[4]]
[1] 4

[[5]]
[1] 3

[[6]]
[1] 6

Is using xts a requirement or just a thought for a possible solution? Have you tried:

list.stuff[ index.list[[[-1]] ]  <-
  list.stuff[ index.list[[-length(index.list)]] ]

Then, if required:

 list.stuff[ index.list[[[1]] ]  <- NULL # or some other value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM