You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中查找数据框各列首次满足指定阈值条件的行号实现方法

R语言查找数据框各列数值首次达阈值对应行号的实现方法

示例数据准备

Data = data.frame(
  Time = seq(1,5),
  V1 = c(0.1, 0.2, 0.4, 0.7, 0.9),
  v2 = c(0.1, 0.12, 0.41, 0.72, 0.91),
  v3 = c(0.03, 0.13, 0.62, 0.50, 0.90)
)

本次需求的判定阈值设为0.6。


实现方案

方案1:基础R实现(无需加载第三方包)

核心思路是对除时间列外的每一列,通过逻辑判断定位第一个满足阈值条件的位置:

threshold <- 0.6
# 排除Time列,逐列计算首次达阈值的行号
result <- as.data.frame(t(apply(Data[, !names(Data) %in% "Time"], 2, function(col) {
  # 优先返回第一个满足条件的行号,若整列都不满足则返回NA
  if (any(col >= threshold)) which.max(col >= threshold) else NA
})))

输出结果:

V1 v2 v3
1  4  4  3

方案2:tidyverse语法实现

适合习惯tidy生态的用户,代码更简洁:

library(dplyr)

threshold <- 0.6
result <- Data %>%
  # 排除不需要计算的Time列
  select(-Time) %>%
  # 对所有列计算首次达阈值的位置
  summarise(across(everything(), ~which.max(.x >= threshold)))

运行后得到的结果和基础R方案完全一致。


内容的提问来源于stack exchange,提问作者Vinicius B. de S. Moreira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:54:03