Write a loop for my function in r

2019-09-13 23:58发布

问题:

I am currently trying to write my first loop for lagged regressions on 30 variables. Variables are labeled as rx1, rx2.... rx3, and the data frame is called my_num_data.

I have created a loop that looks like this:

z <- zoo(my_num_data)

for (i in 1:30)
{dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1) 
        + lag(my_num_data$rx[i], 2))
}

But I received an error message:

Error in model.frame.default(formula = dyn(my_num_data$rx[i] ~ lag(my_num_data$rx[i], : invalid type (NULL) for variable 'my_num_data$rx[i]'

Can anyone tell me what the problem is with the loop?

Thanks!

回答1:

First problem, I'm pretty sure the function you're looking for is dynlm(), without the $ character. Second, using $rx[i] doesn't concatenate rx and the contents of i, it selects the (single) element in $rx with index i. Try this... edited I don't have your data, so I can't test it on my machine:

results <- list()
for (i in 1:30) {
  results[[i]] <- dynlm(my_num_data[,i] ~ lag(my_num_data[,i], 1) 
    + lag(my_num_data[,i], 2))
}

and then list element results[[1]] will be the results from the first regresssion, and so on.

Note that this assumes your my_num_data data.frame ONLY consists of columns rx1, rx2, etc.



回答2:

This produces a list, L, whose ith component has the name of the ith column of z and whose content is the regression of the ith column of z on its first two lags. Lag is same as lag except for a reversal of argument k's sign.

library(dyn)
z <- zoo(anscombe) # test input using builtin data.frame anscombe

Lag <- function(x, k) lag(x, -k)
L <- lapply(as.list(z), function(x) dyn$lm(x ~ Lag(x, 1:2)))


回答3:

I am not super familiar with R, but it appears you are trying to increase the index of rx. Is rx a vector with values at different indices? If not the solution my be to concatenate a string

for (i in 1:30){
varName <-- "rx"+i
dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1) 
        + lag(my_num_data$varName, 2))
}

Again, I may be way off here, as this if my first post and R is still pretty new to me.