R语言如何通过for循环结合dataframe双条件计算TP、TN并存储结果
你遇到的问题核心是循环过程中没有将每次计算的TP、TN存入指定存储位置,变量被反复覆盖,因此只能保留最后一次循环的结果。以下是符合你需求的实现方案:
实现代码(循环版,适合新手理解)
# 提取所有阈值 thresholds <- df$B n <- length(thresholds) # 按照你要求的列结构初始化结果框 results <- data.frame( B = rep(c("mass", "not mass"), each = n), A = rep(thresholds, 2), TP = integer(2 * n), TN = integer(2 * n) ) # 循环计算每个阈值对应的TP、TN并赋值 for (i in seq_along(thresholds)) { current_thresh <- thresholds[i] # 计算mass类对应的统计值 tp_mass <- sum(df$A == "mass" & df$B >= current_thresh) tn_mass <- sum(df$A != "mass" & df$B <= current_thresh) results$TP[i] <- tp_mass results$TN[i] <- tn_mass # 计算not mass类对应的统计值,可根据实际统计规则修改条件 tp_notmass <- sum(df$A != "mass" & df$B <= current_thresh) tn_notmass <- sum(df$A == "mass" & df$B >= current_thresh) results$TP[n + i] <- tp_notmass results$TN[n + i] <- tn_notmass }
优化方案(向量化写法,效率更高)
如果数据集规模更大,推荐用向量化操作替代显式循环:
thresholds <- df$B n <- length(thresholds) # 批量计算所有阈值对应的统计值 tp_mass_vec <- sapply(thresholds, function(x) sum(df$A == "mass" & df$B >= x)) tn_mass_vec <- sapply(thresholds, function(x) sum(df$A != "mass" & df$B <= x)) # 直接构造结果框 results <- data.frame( B = rep(c("mass", "not mass"), each = n), A = rep(thresholds, 2), TP = c(tp_mass_vec, tn_mass_vec), TN = c(tn_mass_vec, tp_mass_vec) )
补充说明
如果df$B存在大量重复阈值,可以将thresholds <- df$B替换为thresholds <- unique(df$B),避免重复计算,结果行数也会对应减少。
内容的提问来源于stack exchange,提问作者FinalsWeek
相关产品推荐
相关产品推荐

