Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping across time series values in R

I apologize if I have overlooked a solution to this somewhere, but I have spent what seems like an unjustifiable amount of time trying to get a solution to this. I want to manipulate multiple time series values and a solution to the simple task below may help:

x1 <- c(1, 11, 21)
y1 <- c(2, 12, 22)
x2 <- c(3, 13, 23)
y2 <- c(4, 14, 24)
x3 <- c(5, 15, 25)
y4 <- c(6, 16, 26)

Assume the above values go up to x60 and y60.

z1 <- x1 + y1
z2 <- x2 + y2 
z3 <- x3 + y3

I need to generate the values z1, z2… with loops. Something along the lines of:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (i in 1:3){
  obj1= paste0("x",i)
  obj2= paste0("y", i)
  dv<- paste0("z", i)
  assign(dv, obj1 + obj2)
}

(ofcourse this doesn’t run). Any ideas?

>Solution :

We can use mget to retrieve the ‘x’ object values into a list and likewise the y object values, then loop over the corresponding list with Map and add them (+) and return a list. If we need to create ‘z’ objects in the global env (not recommended), set the names of the output list with ‘z1’, ‘z2’, etc and then use list2env

lst1 <- Map(`+`, mget(ls(pattern = "^x\\d+$")),
                 mget(ls(pattern = "^y\\d+$")))
names(lst1) <- paste0("z", seq_along(lst1))
list2env(lst1, .GlobalEnv)

The for loop didn’t run because the operator (+) is applied on the object name strings and not the value. We can use get here

for (i in 1:3){
  obj1= paste0("x",i)
  obj2= paste0("y", i)
  dv<- paste0("z", i)
  assign(dv, get(obj1) + get(obj2))
}

For the edited case, we may do

fmla <- paste0(paste0("psr_", 1:60), "~", paste0("unemp_", 1:60))
lapply(fmla, function(fml) td(as.formula(fml), "average"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading