将函数应用于多列

Applying a function to multiple columns

我想将一个函数应用于多个列。我在数据框 data 中的数据结构如下:

col1 col2 col3
x    x    x
x    x    x
x    x    x

特别是,我想对每一列的时间序列应用 ADF 测试。

我认为这样的方法可能有效:

f <- function(x) ur.df(x, type = "none", lags = 10, selectlags = "AIC"))
sapply(data, f)

但是,处理列的 "variable" 似乎有问题。

如何正确完成?

更新:使用它创建具有随机值的三列:

data = data.frame(matrix(rnorm(30), nrow=10))

据我所知,您的代码存在两个问题:

1) 在你的函数定义中,你的一个括号太多了;应该是:

f <- function(x) ur.df(x, type = "none", lags = 10, selectlags = "AIC")

2) 对于给定的数据集维度,滞后数过高。以下作品(分别注意不同数据集的不同维度和滞后):

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)

给出以下输出(数字当然可以不同,因为我没有为 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

$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