DON_DON
DON_DON

Reputation: 99

Extracting data in a list within a list in R (subsetting list within a list)

I have a list of 3 and within each of those list is another list of two time series. code down below would explain how my situation is:

set.seed(12)
dummy.df <- as.data.frame(matrix(round(rnorm(1200),digits=2),nrow=100,ncol=12))
rownames(dummy.df) <- seq(from=1901, to=2000)
colnames(dummy.df) <- c("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec")
dummy.df.ts <- ts(as.vector(as.matrix(dummy.df)), start=c(1901,1), end=c(2000,12), frequency=12)
dummy.df.ts

I would Create 6 dummy list till dummy.df.5 and create the dummy nested list as below:

lit1 <- list(dummy.df.ts,dummy.df1.ts)
lit2 <- list(dummy.df2.ts,dummy.df3.ts)
lit3 <- list(dummy.df4.ts,dummy.df5.ts)
finaldata <- list(lit1,lit2,lit3)

and each time series would look like below:
enter image description here

I would then apply this code to achive the min and max values from each 3 list:

sapply(finaldata, function(x)range(x))


to get this results:

enter image description here

How would i be able to extract the year and the month of each following min and max value obtained from the function range? I Would like to know how to extract/subset the following nested string of time series.

Upvotes: 1

Views: 44

Answers (1)

akrun
akrun

Reputation: 886998

Convert to an xts objects and then the index or rownames will be the year and month

library(xts)
do.call(rbind, lapply(finaldata, function(x) do.call(rbind,
     lapply(x, function(y)  {xt1 <- as.xts(y)
       subset(xt1, xt1 %in% range(xt1))}))))

Or with rapply

do.call(rbind, do.call(c, rapply(finaldata, function(x) {
   xt1 <- as.xts(x)
   subset(xt1, xt1 %in% range(xt1))}, how = 'list')))

Or another option is to get the corresponding time, convert to year mon with as.yearmon from zoo

library(zoo)
unlist(lapply(finaldata, function(x) 
  lapply(x, function(y) as.character(as.yearmon(time(y))[y %in% range(y)]))))

Upvotes: 1

Related Questions