【发布时间】:2018-04-16 20:00:04
【问题描述】:
我正在尝试在 R 中编写我的第一个 for 循环。该循环应读取物种列表,确定每个物种的 AUC 和 Kappa 值,然后将数据写入 .csv 文件。
为了简化,我暂时省略了代码的 Kappa 部分。代码运行良好,但我得到的 csv 文件的输出是我列表中的最后一个物种,并且相应的 AUC 重复了 15 次。
相反,如果我运行 print(i) 和 print(AUC),我会得到每个物种的列表和相应的 AUC。我不明白为什么print 和write.csv 没有给我相同的结果。
setwd("Y:/HModel/Maxent/MaxentOutputs/allspp 11-28")
splist <-c( "pomatomus_saltatrix",
"stenotomus_chrysops",
"illex_illecebrosus",
"lophius_americanus",
"squalus_acanthias",
"scophthalmus_aquosus",
"paralichthys_dentatus",
"helicolenus_dactylopterus",
"merluccius_albidus",
"merluccius_bilinearis",
"urophycis_chuss",
"cynoscion_regalis",
"pollachius_virens",
"urophycis_tenuis",
"tautogolabrus_adspersus")
n = rep(NA, length(splist))
AUCandKAPPA = data.frame(sppocean=n, AUC=n, stringsAsFactors=FALSE)
for (i in splist) {
presence_csv <- paste(i,"0", "samplePredictions.csv", sep = "_")
background_csv <- paste(i, "0", "backgroundPredictions.csv", sep = "_")
presence <- read.csv(presence_csv)
background <- read.csv(background_csv)
pp <- presence$Logistic.prediction # get the column of predictions
testpp <- pp[presence$Test.or.train=="test"] # select only test points
trainpp <- pp[presence$Test.or.train=="train"] # select only test points
bb <- background$Logistic
combined <- c(testpp, bb) # combine into a single vector
label <- c(rep(1,length(testpp)),rep(0,length(bb))) # labels: 1=present, 0=random
pred <- prediction(combined, label) # labeled predictions
perf <- performance(pred, "tpr", "fpr") # True / false positives, for ROC curve
AUC <-performance(pred, "auc")@y.values[[1]] # Calculate the AUC
# fill in diagnostics
AUCandKAPPA$sppocean = i
AUCandKAPPA$AUC = AUC
print(i)
print(AUC)
# write AUC and kappa to excel file
write.csv(AUCandKAPPA, file="kappa_sp1-28.csv")
}
我尝试更改以下行,但出现错误
# fill in diagnostics
AUCandKAPPA$sppocean[i] = i
AUCandKAPPA$AUC[i] = AUC
Error in `$<-.data.frame`(`*tmp*`, "sppocean", value = c("15", "pomatomus_saltatrix" :
replacement has 2 rows, data has 1
【问题讨论】: