I have a list with a rather complex structure from which I want to extract only a few specific values. Since the dput
output of the data and the structure of the list seems to be problematic in this case, I reproduce here the code posted yesterday by @user34771 that was used to generate this list:
set.seed(123)
testdf <- data.frame(vy = rnorm(60), vx = rnorm(60) , gvar = rep(c("a","b"), each=30))
require(fBasics)
normfuns <- list(jarqueberaTest=jarqueberaTest, shapiroTest=shapiroTest, lillieTest=lillieTest)
mynormtest <- function(d) {
norm_test <- res_reg <- list()
for (i in c("a","b")){
res_reg[[i]] <- residuals(lm(vy~vx, data=d[d$gvar==i,]))
norm_test[[i]] <- lapply(normfuns, function(f) f(res_reg[[i]]))
}
return(norm_test)
}
res_list <- mynormtest(testdf)
For the data in res_list
, I have a function that extracts the values that I'm interested in and stores them in a matrix:
getparams2 <- function(myp) {
m <- matrix(NA, nrow=length(myp), ncol=3)
for (i in (1:length(myp))){
m[i,] <- sapply(1:3,function(x) myp[[i]][[x]]@test$statistic)}
return(m)
}
This function provides the desired output.
> getparams2(res_list)
[,1] [,2] [,3]
[1,] 0.9917054 0.9670860 0.08837058
[2,] 0.1421776 0.9806379 0.12619274
However, I'm not happy with the style of the function getparams2()
with its FOR
loop. I'd be glad to know if this function can be written in a more elegant and more compact form. Thank you for your help.
To get a matrix:
t(sapply(res_list, sapply, function(x) x@test$statistic))
# jarqueberaTest.X-squared shapiroTest.W lillieTest.D
#a 0.9917054 0.9670860 0.08837058
#b 0.1421776 0.9806379 0.12619274
Or with rapply
:
t(simplify2array(rapply(res_list, function(x) x@test$statistic, how = "list")))
# jarqueberaTest shapiroTest lillieTest
#a 0.9917054 0.967086 0.08837058
#b 0.1421776 0.9806379 0.1261927
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.