Question

I am trying to write a function in R, for a simple time series regression (the result of this function is the output for more complicated ones). In the first part i define the variables and create some lags for the function, which are named ar_i depending on the used lag.

However in the second part i try to combine this lags in a matrix using a cbind function on the variables initially defined. As you can see the output is not the expected matrix, but the names of the lags themselves. I tried to solve this by using the noquote() and cat() function, but these don't seem to work.

Do you have any suggestions? Thanks in advance!!!

Pd: The code and the results are below.

trans      <- dlpib
ar         <- dlpib
linear     <- 1:4

for (i in linear){
  assign(paste("ar_",i,sep = ""), lag(ar,k=-i))
}

linear_dat <- cbind(paste("ar_",linear, collapse=',', sep = ""))

> linear_dat
     [,1]                 
[1,] "ar_1,ar_2,ar_3,ar_4"
Was it helpful?

Solution

I think you could go about this more efficiently with sapply:

linear <- 1:4
linear_list <- lapply(linear, function(i) lag(ar, k=-i))
linear_dat <- do.call(cbind, linear_list)
colnames(linear_dat) <- paste0("ar_", linear)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top