问题
I want to apply a function to multiple columns. My data in the dataframe data
is structured as follows:
col1 col2 col3
x x x
x x x
x x x
In particular, I want to apply an ADF test on the time-series of each column.
I thought something like this might work:
f <- function(x) ur.df(x, type = "none", lags = 10, selectlags = "AIC"))
sapply(data, f)
However, it seems that there's a problem handling the "variable" of the column.
How is it done correctly?
Update: Use this to create three columns with random values:
data = data.frame(matrix(rnorm(30), nrow=10))
回答1:
There are two issues with your code as far as I can see:
1) In your function definition, you have one parenthesis too much; it should be:
f <- function(x) ur.df(x, type = "none", lags = 10, selectlags = "AIC")
2) The number of lags is too high for the given dimension of the dataset. The following works (note the different dimensions and lags of and for the different datasets, respectively):
library(urca)
data <- data.frame(matrix(rnorm(300), nrow=100))
f <- function(x) ur.df(x, type = "none", lags = 10, selectlags = "AIC")
sapply(data,f)
data2 = data.frame(matrix(rnorm(30), nrow=10))
f2 <- function(x) ur.df(x, type = "none", lags = 3, selectlags = "AIC")
sapply(data2,f2)
which gives you the following output (numbers can of course differ since I did not set a seed for rnorm
):
$X1 Augmented Dickey-Fuller Test Unit Root / Cointegration Test The value of the test statistic is: -6.0255
$X2 Augmented Dickey-Fuller Test Unit Root / Cointegration Test The value of the test statistic is: -7.164
$X3 Augmented Dickey-Fuller Test Unit Root / Cointegration Test The value of the test statistic is: -5.0921
and
$X1 Augmented Dickey-Fuller Test Unit Root / Cointegration Test The value of the test statistic is: -1.2124
$X2 Augmented Dickey-Fuller Test Unit Root / Cointegration Test The value of the test statistic is: -0.8715
$X3 Augmented Dickey-Fuller Test Unit Root / Cointegration Test The value of the test statistic is: -0.6598
来源:https://stackoverflow.com/questions/32570988/applying-a-function-to-multiple-columns