我正在分析一項隨機對照試驗,并正在研究治療*時間互動測驗。我希望將 ANOVA 的 p 值提取到資料框中以匯出到 excel 中。目前,我的代碼將一個物件編程為 p 值作為維度 [1:4] 的數值向量。但是,當我將其復制到 excel 中時,資料將被轉錄到每行一個單元格中,其中的值由空格分隔,而不是每個 p 值占據自己的單元格。
library(tidyverse)
library(rstatix)
library(lme4)
set.seed(42)
n <- 1000
dat1 <- data.frame(id=1:n,
treat = factor(sample(c('Trt','Ctrl'), n, rep=TRUE, prob=c(.5, .5))),
time = factor("T1"),
outcome1=rbinom(n = 1000, size = 1, prob = 0.3),
st=runif(n, min=24, max=60),
qt=runif(n, min=.24, max=.60),
zt=runif(n, min=124, max=360)
)
dat2 <- data.frame(id=1:n,
treat = dat1$treat,
time = factor("T2"),
outcome1=dat1$outcome1,
st=runif(n, min=24, max=60),
qt=runif(n, min=.24, max=.60),
zt=runif(n, min=124, max=360)
)
dat <- rbind(dat1,dat2)
id <- dat$id
st <- dat$st
qt <- dat$qt
zt <- dat$zt
treat <- dat$treat
time <- dat$time
plist<- list("st","qt", "zt")
for (i in plist){
model <- lmer(paste(i, "~ (treat*time)", " (1|id)"), data=dat)
anovamodel <- (Anova(model, type=3))
grpxtime <- anovamodel$`Pr(>Chisq)`
print(grpxtime)
}
uj5u.com熱心網友回復:
幾點。
- 最好不要
plist用作索引,而是使用 with 呼叫的seq_len()輸出length(plist)。 - 我們可以將 p 值存盤在一個矩陣中,我們通常稱之為
out。然后我們將列名分配給out,以便更容易理解哪個 p 值屬于哪個固定效應。 - 我們觀察到其中一個模型很難估計隨機效應的方差,因為它回傳
boundary (singular) fit: see ?isSingular。如果您使用自己的(非模擬)資料對此進行處理,則需要您注意。有關詳細資訊,請參閱此頁面。
## snip ##
plist<- list("st","qt", "zt")
X <- model.matrix(~ treat * time, data = dat)
out <- matrix(rep(0L, length(plist) * dim(X)[2L]), ncol = 4L)
for (i in seq_len(length(plist))){
model <- lmer(paste(plist[i], "~ (treat*time)", " (1|id)"), data=dat)
anovamodel <- (Anova(model, type=3))
out[i, ] <- anovamodel$`Pr(>Chisq)`
}
colnames(out) <- colnames(model.matrix(model))
# --------------------------------------------------
> out
(Intercept) treatTrt timeT2 treatTrt:timeT2
[1,] 0 0.3149593 0.7015615 0.3278066
[2,] 0 0.7774849 0.3511975 0.9013959
[3,] 0 0.5941231 0.1599605 0.9484378
我們可以保存out為 .csv 檔案以供以后在 Excel 中使用。
# specify the folder where the file is to be stored
projdir <- 'my_directory'
write.csv(out, file = file.path(projdir, 'my_pvals.csv'))
# -----------------------------------------------------------------------
## write.csv2(out, file = file.path(projdir, 'my_pvals.csv'))
## to use a comma for the decimal point and a semicolon for the separator
## the Excel convention for CSV files in some Western European locales
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/419370.html
標籤:
上一篇:R管道運算子%T>%
