amal
amal

Reputation: 13

How to modify the code for p-values (lapply R)

I can extract the p-value (df2) if I define modelList in this way

responseList <- names(mtcars)[-c(4,9)]
modelList    <- lapply(responseList, function(resp) {
                           mF <- formula(paste(resp, " ~ hp*am"))
                           aov(mF, data = mtcars)
                })
df2 <- plyr::ldply( modelList , function(x) summary(x)[[1]][["Pr(>F)"]])
names(df2) <- c(attr(modelList[[1]]$terms, "term.labels"), "residuals")

However if I define ModelList in the following way, I can not get the result.

formula <- as.formula(paste0("cbind(", paste(names(mtcars)[-c(4,9)], collapse = ","), ") ~ hp*am"))
modelList  <- aov(formula, data=mtcars) 

So how can I modify df2 in order to extract the pvalues from the second defined function for modelList.

df2 <- plyr::ldply( modelList , function(x) summary(x)[[1]][["Pr(>F)"]])
    names(df2) <- c(attr(modelList[[1]]$terms, "term.labels"), "residuals")

Upvotes: 1

Views: 90

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24252

Here is one of the possible ways for extracting p-values from the second modelList.

formula <- as.formula(paste0("cbind(", paste(names(mtcars)[-c(4,9)], collapse = ","), ") ~ hp*am"))
modelList2  <- aov(formula, data=mtcars) 

df2 <- plyr::ldply( summary(modelList2), function(x) x[,"Pr(>F)"])
names(df2) <- c("", rownames(modelList2[[1]])[-1], "residuals") 
df2

################
                           hp           am        hp:am residuals
1   Response mpg 1.504500e-09 4.748593e-05 0.9806460396        NA
2   Response cyl 3.974632e-11 2.997217e-04 0.0969093688        NA
3  Response disp 5.835767e-11 1.164601e-05 0.0178673463        NA
4  Response drat 9.236405e-04 1.911898e-05 0.8664040719        NA
5    Response wt 1.348501e-07 2.977105e-06 0.1913211750        NA
6  Response qsec 2.312064e-07 4.577810e-04 0.1767439339        NA
7    Response vs 2.060911e-06 9.495711e-01 0.0458841894        NA
8  Response gear 1.696824e-01 1.405025e-09 0.0002293635        NA
9  Response carb 3.077405e-07 3.622291e-02 0.1902486095        NA

Upvotes: 1

Related Questions