Home > Blockchain >  Looping across time series values in R
Looping across time series values in R

Time:08-03

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:

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?

CodePudding user response:

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)

NOTE: Here we used Map as the lengths can also be different for each of the vector objects


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"))

CodePudding user response:

In general one does not use individual variables but rather collects them into data frames, matrices or other structures. Here we put the x variables into X, the y variables into Y and the sums into Z.

X <- as.data.frame(mget(ls(pattern = "^x\\d $")))
Y <- as.data.frame(mget(ls(pattern = "^y\\d $")))
Z <- X   Y
names(Z) <- sub(".", "z", names(Z))

Z
##   z1 z2 z3
## 1  3  7 11
## 2 23 27 31
## 3 43 47 51

Z[[2]]  # get z2
## [1]  7 27 47

Z$z2 # same
## [1]  7 27 47
  • Related