我有下面的代码,我想为它构建一个循环:
Ten0 = dbGetQuery(conn, "select * from yyyy where tenure=0")
Ten0_alg = readRDS(file = "t0_scoring.rda")
new <- survfit(Ten0_alg, newdata = Ten0)
Ten0_scored <- cbind(Ten0,tmp)
我想要做的是将数字0从0增加到24,并在每次数字以自动方式递增时执行代码。
任何帮助都会很棒。
由于
答案 0 :(得分:0)
免责声明:
虽然可以使用具有“变量varnames”的循环执行此操作,但您可以考虑调整数据结构,使其不依赖于“变量varnames”
如何在R中执行变量varnames:
使用eval-parse技巧,其中命令是使用相应命令解析和评估的字符串。
for (i in 0:24) {
cmd <- paste0("Ten",i," = dbGetQuery(conn, \"select * from yyyy where tenure=",i,"\");
Ten",i,"_alg = readRDS(file = \"t",i,"_scoring.rda\");
new <- survfit(Ten",i,"_alg, newdata = Ten",i,");
Ten",i,"_scored <- cbind(Ten",i,",tmp)")
eval(parse(text=cmd))
}
此代码块是通过在您提供的代码中将"
替换为\"
而0
替换为",i,"
而生成的。
您可以做什么:
?lapply
),例如: tenures <- 0:24
Tan <- lapply(tenures, function(x) dbGetQuery(conn, paste0("select * from yyyy where tenure=",x))
getResults <- function(conn, file, tenure) {
Ten0 = dbGetQuery(conn, paste0("select * from yyyy where
tenure=",tenure))
Ten0_alg = readRDS(file = file)
new <- survfit(Ten0_alg, newdata = Ten0)
Ten0_scored <- cbind(Ten0,tmp)
# return all results
return(list(Ten0=Ten0,Ten0_alg=Ten0_alg,new=new,Ten0_scored=Ten0_scored))
}