我的R代码有一个小问题。我认为这很容易解决,但是我对R的经验很少。
我有一个线性模型,使用drop1函数后,我有了p值(请参见下面的代码)。我已经在我的第一学期A1中做到了这一点。
因此,我想对A2 A3进行相同操作,依此类推,并希望将所有p值存储在一个文件中。我需要提取sie p值并使用某种循环。我需要什么样的功能?如何提取p值?
mod1<-lm(A1~B+C, data=ipo)
drop1(mod1, test="F")
dput(head(ipo, 20))
structure(list(C = c(461.875, 441.85, 2133.025, 2213.704167,
1533.120833, 1423.529167, 1011.6875, 985.1, 221.2708333, 200.1291667,
336.875, 310.6875, 228.7583333, 220.4875, 452.7416667, 435.5416667,
242.0041667, 232.4833333, 411.4458333, 412.5875), A1 = c(32925L,
30797L, 162617L, 159828L, 110595L, 112922L, 78285L, 73708L, 14542L,
14271L, 24484L, 23792L, 18269L, 15513L, 34383L, 32109L, 16531L,
17279L, 30179L, 29919L), A2 = c(32925L, 30797L, 162617L, 159828L,
110595L, 112922L, 78285L, 73708L, 14542L, 14271L, 24484L, 23792L,
18269L, 15513L, 34383L, 32109L, 16531L, 17279L, 30179L, 29919L
), B = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C",
"D", "E", "F", "G", "H"), class = "factor")), .Names = c("C",
"A1", "A2", "B"), row.names = c(NA, 20L), class = "data.frame")
答案 0 :(得分:1)
您可以尝试$ [sudo] gem install cocoapods --pre
tidyverse
答案 1 :(得分:0)
此解决方案使用包reshape2
和函数melt
来将数据从宽格式整形为长格式。其余的仅是基数R。
long <- reshape2::melt(ipo, id.vars = c("B", "C"))
sp <- split(long, long$variable)
res <- lapply(sp, function(DF){
fit <- lm(value ~ B + C, data = DF)
d <- drop1(fit)[-1, ]
attr(d, "heading") <- NULL
d
})
do.call(rbind, res)
# Df Sum of Sq RSS AIC
#A1.B 2 8.3683e+05 1.2415e+08 316.83
#A1.C 1 1.8533e+10 1.8656e+10 419.07
#A2.B 2 8.3683e+05 1.2415e+08 316.83
#A2.C 1 1.8533e+10 1.8656e+10 419.07
答案 2 :(得分:0)
这里是仅提取p值的基本R解决方案。这应该可以帮助您入门-如果您无法按照自己的意愿更改输出,请告诉我。祝你好运!
# Get DV names
dvs <- names(ipo)[2:3]
# Create formula objects
formula_text <- paste0(dvs, " ~ B + C")
formulas <- lapply(formula_text, formula)
# Run models with drop1
models <- lapply(formulas, function(x){
drop1(lm(x, data = ipo), test = "F")
})
# Extract p-values
model_pvals <- lapply(models, function(x) x[["Pr(>F)"]])
# Name and turn list into dataframe
names(model_pvals) <- formula_text
do.call(rbind, model_pvals)
[,1] [,2] [,3]
A1 ~ B + C NA 0.9473321 7.177227e-19
A2 ~ B + C NA 0.9473321 7.177227e-19