0

Assume we have following table where we have each two pairs of variables to be tested with each other (the original table has far more columns):http://pastebin.com/igeMTaSB

How can I create a loop in R so that it applies a function each one or two rows in a script?

Example Code:

library(urca)
library(lmtest)

# Load data (See link)

table = read.csv("test.csv", header = TRUE, sep=",")
table = data.frame(table)
table

# For each column in the table (a1-d2), do
VARselect(table$column,lag.max = 10,type="both")

# For each two sequent pairs in the table (a1+a2, b1+b2,c1+c2,d1+d2), do
grangertest(table$a1, table$a2, order = 1, na.action = na.omit)
1
  • For the one variable case, use sapply or lapply: lapply(table, function(i) VARselect(i,lag.max = 10,type="both")). Commented Jun 24, 2016 at 12:13

1 Answer 1

1

For the one variable case, use sapply or lapply, for example:

myVarSel <- lapply(table, function(i) VARselect(i,lag.max = 10,type="both"))

If your pairs of variables are located adjacently (columns 1,2 and 3,4 and 5,6), you can use lapply as follows:

myGtests <- lapply(seq(1, 5, 2), function(i) grangertest(table[[i]], table[[i+1]], order = 1,
                                             na.action = na.omit))

If the variables are arranged in a different manner, you can use tools like grep on the names(df) to locate them. for extraction in lapply.

The lapply function returns a list, where each element is the result of the corresponding function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.