I would like to extract all teststat
from a list. Manually, I can achieve the expected result. Here is the code:
library(urca)
set.seed(1234)
df_example <- data.frame(a = rnorm(75), b = rnorm(75), c = rnorm(75), d = rnorm(75))
df_UR_pp <- lapply(
df_example,
function(x){
ur.pp(x, type = "Z-tau", model = "constant", lags = "short")
}
)
# Problem is here
all_results <- lapply(df_UR_pp, `[`, 'teststat')
#> Error in FUN(X[[i]], ...): object of type 'S4' is not subsettable
# Expected result
table_all_results <- data.frame("Variable" = c("a", "b" , "c", "d"),
"Z-tau statistic" = c(df_UR_pp$a@teststat, df_UR_pp$b@teststat, df_UR_pp$c@teststat, df_UR_pp$d@teststat))
table_all_results
#> Variable Z.tau.statistic
#> 1 a -7.650956
#> 2 b -7.396869
#> 3 c -7.402462
#> 4 d -8.256534
You can just use an anonymous function that uses @
:
lapply(df_UR_pp, function(x) x@teststat)
$a
[1] -7.650956
$b
[1] -7.396869
$c
[1] -7.402462
$d
[1] -8.256534
Or, you could call slot()
in the lapply()
call:
lapply(df_UR_pp, slot, 'teststat')
$a
[1] -7.650956
$b
[1] -7.396869
$c
[1] -7.402462
$d
[1] -8.256534
(Credit to @Roland for this suggestion)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.