2

I'm struggling with analyzing values in a rather complex list with vectors. It is a list with coefficients (=vector) of applying ARIMA testing to a number of time series.

These coefficient vectors may be empty (numeric(0)), or of different sizes. An example:

> test <- list(numeric(0),c(ma1=0.7712434), c(ar1=0.6438842, ar2=-0.3112884))
> test
[[1]]
numeric(0)

[[2]]
      ma1 
0.7712434 

[[3]]
       ar1        ar2 
 0.6438842 -0.3112884 

I want to be able to easy select all the 'ar' or 'ar1' terms for instance (selection based on the name). I'm struggling handling this complex list. So I think the easiest solution is to transform this list of vectors into a single vector (ignoring the empty numerics).

For the example above resulting in:

> c(ma1=0.7712434, ar1=0.6438842, ar2=-0.3112884)
       ma1        ar1        ar2 
 0.7712434  0.6438842 -0.3112884

Who's able to help me out??

Note: I was able to calculate the number of, lets say, AR terms, based on their names, see below. But I'm not able to use this in extracting the actual values of those terms.

tempFunName <- function(vec, name) { substr(names(vec),1,2) == name } # info on coef types
termType <- "ar" # all names starting with "ar"
sum(sapply(lapply(test, tempFunName, name=termType), sum, simplify=TRUE)) # all names starting with "ar"
FBE
  • 631
  • 2
  • 8
  • 15

1 Answers1

2

One way would be:

unlist(test)[grep("^ar", names(unlist(test)))]

unlist() just makes the list into a vector, and from there we can subset with name matching via grep. The ^ means to search for the pattern at the start of the name.

If you want to keep the output in list form, you can try:

lapply(test, function(x) x[grep("^ar", names(x))])

Update: Examples

Note: I've added a few more variables to your example data for illustration purpose.

test <- list(numeric(0),
             c(ma1 = 0.7712434, star = .001),
             c(ar1 = 0.6438842, ar2 = -0.3112884, par = 0.12345))
lapply(test, function(x) x[grep("ar", names(x))])
# [[1]]
# numeric(0)
# 
# [[2]]
#  star 
# 0.001 
# 
# [[3]]
#       ar1        ar2        par 
# 0.6438842 -0.3112884  0.1234500 
lapply(test, function(x) x[grep("^ar", names(x))])
# [[1]]
# numeric(0)
# 
# [[2]]
# named numeric(0)
# 
# [[3]]
#       ar1        ar2 
# 0.6438842 -0.3112884 
unlist(lapply(test, function(x) x[grep("^ar", names(x))]))
#       ar1        ar2 
# 0.6438842 -0.3112884 
A5C1D2H2I1M1N2O1R2T1
  • 177,446
  • 27
  • 370
  • 450
  • Both @ttmaccer and @mrdwab; thanks for the answers. Both `unlist` and `do.call("c", ...)` result in the same. For calculation time reasons I go for the `unlist` solution: system.time for unlist = 0.72, for do.call = 1.31. Although both are taking a small amount of time, I will choose the fastest :) – FBE Aug 10 '12 at 11:22