如何编写一个函数或循环来遍历这个使用mstate()包的过程,它使用了多个嵌套框架(cohort 1-cohort 25)?
样本数据:
impute1 <- data.frame(unique_ID = c(1,2,3,4),
DIED_INDICATOR = c(0,1,1,1),
CVD_ANY = c(0,1,1,0),
YEARS_CVD_DEATH = c(15.9, 23.6, 22.7, 3.4),
YEARS_CVD_HOSP = c(15.9, 11.4, 22.7, 3.4),
TOBACCO = c(0, 0, 0, 1),
MARRIED = c(1,0,1,0),
PARITY = c(2,1,1,2))
impute2 <- data.frame(unique_ID = c(1,2,3,4),
DIED_INDICATOR = c(0,1,1,1),
CVD_ANY = c(0,1,1,0),
YEARS_CVD_DEATH = c(15.9, 23.6, 22.7, 3.4),
YEARS_CVD_HOSP = c(15.9, 11.4, 22.7, 3.4),
TOBACCO = c(0, 1, 0, 1),
MARRIED = c(1,0,1,1),
PARITY = c(1,1,1,2))
covs<-c("TOBACCO", "MARRIED", "PARITY")
字符串
在1个框架上运行模型的代码:
cohort1 <- msprep(data=impute1,trans=tmat,
time=c(NA,"YEARS_CVD_HOSP","YEARS_CVD_DEATH"),
status=c(NA,"CVD_ANY","DIED_INDICATOR"),
keep=covs,
id = as.vector(impute1$unique_ID))
cohort_expand<-expand.covs(cohort1, covs, append = TRUE, longnames = FALSE)
c1<-coxph(Surv(Tstart, Tstop, status)~TOBACCO.1 + TOBACCO.2 +
TOBACCO.3 + strata(trans), data=cohort1, method = "breslow")
summary(c1)
newdata<-data.frame(trans=1:3, TOBACCO.1 = c(0,0,0), TOBACCO.2 =
c(0,0,0), TOBACCO.3 = c(0,0,0), strata = 1:3)
msf1<-msfit(c1, newdata, trans=tmat)
plot(msf1, las=1, lty=rep(1:2,c(8,4)), xlab="Years")
型
我把25个字符串放入一个列表中:
path <- ''
print(path)
files <- list.files(path = path, pattern="*.sas7bdat", full.names=FALSE)
print(files)
impute <- list()
for (i in 1:length(files)){
filename <- paste0(path, files[i])
print(filename)
impute[[i]] <- haven::read_sas(data_file=filename)
print(names(impute[[i]]))
eval(parse(text = paste0("impute", i, " <-
haven::read_sas(data_file=filename)")))
}
型
我正在尝试使用前两个估算数据集为msprep步骤编写一个函数。
test_list <- list(impute1, impute2)
my_func <- function(x) {
cohort<-mstate::msprep(data=test_list,trans=tmat,
time=c(NA,"YEARS_CVD_HOSP","YEARS_CVD_DEATH"),
status=c(NA,"CVD_ANY","DIED_INDICATOR"),
keep=covs,
id = as.vector(test_list$unique_ID))
}
test<-lapply(test_list, my_func)
型
我得到一个错误:
mstate中出错::msprep(data = test_list,transs = tmat,time = c(NA,“YEARS_CVD_HOSP”,:参数“id”不是向量
如何将unique_ID指定为向量,即使它是一个列表?
下一个功能:
test<-lapply(test_list, my_func2)
my_func2 <- function(x) {
cohort<-mstate::cohort<-expand.covs(cohort, covs, append =
TRUE, longnames = FALSE)
}
型
我也尝试过使用lapply函数来迭代coxph模型,但是我如何编写整个过程的代码呢?
c1<- lapply(mydf , function(i) {
iformula <- as.formula(sprintf("Surv(Tstart, Tstop, status)
~TOBACCO.1 + TOBACCO.2 + TOBACCO.3 + strata(trans)", i))
})
1条答案
按热度按时间pod7payv1#
我对比例风险回归一无所知,但我也是你的代码,并把它放入一个函数。这是相当简单的,有一个单一的参数,
x
,这是传递给msprep()
中的data
和id
参数。其余的保持不变,除了coxph()
中的data
被更改为cohort_expand
。tmat
和newdata
被移到函数之外,因为它们看起来是恒定的。字符串
的数据