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

如何在R语言中识别数据框列中首个和末个非零值的位置

在R语言数据框中查找首个和末个非零值的位置

首先加载你提供的数据框:

df <- structure(list(`Row Labels` = c("2019-01-01", "2019-02-01", "2019-03-01", "2019-04-01", "2019-05-01", "2019-06-01", "2019-07-01", "2019-08-01", "2019-09-01", "2019-10-01", "2019-11-01", "2019-12-01", "2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01", "2020-06-01", "2020-07-01", "2020-08-01", "2020-09-01", "2020-10-01", "2020-11-01", "2020-12-01", "2021-01-01", "2021-02-01", "2021-03-01", "2021-04-01", "2021-05-01", "2021-06-01", "2021-07-01", "2021-08-01", "2021-09-01", "2021-10-01", "2021-11-01", "2021-12-01", "2022-01-01", "2022-02-01", "2022-03-01", "2022-04-01", "2022-05-01", "2022-06-01", "2022-07-01", "2022-08-01", "2022-09-01", "2022-10-01"), `XYZ|551` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 206, 1814, 2324, 772, 1116, 1636, 1906, 957, 829, 911, 786, 938, 1313, 2384, 1554, 1777, 1635, 1534, 1015, 827, 982, 685, 767, 511, 239, 1850, 1301, 426, 261, 201, 33, 0, 0, 0, 0, 0, 0)), row.names = c(NA, -46L), class = c("tbl_df", "tbl", "data.frame"))

方法一:基础R实现

直接通过索引定位非零值,提取首尾位置:

# 提取目标数值列
target_col <- df$`XYZ|551`

# 获取所有非零值的索引
nonzero_indices <- which(target_col != 0)

# 首个非零值的位置和对应日期
first_pos <- nonzero_indices[1]
first_date <- df$`Row Labels`[first_pos]

# 末个非零值的位置和对应日期
last_pos <- tail(nonzero_indices, 1)
last_date <- df$`Row Labels`[last_pos]

# 输出结果
cat("首个非零值位于第", first_pos, "行,日期:", first_date, "\n")
cat("末个非零值位于第", last_pos, "行,日期:", last_date, "\n")

运行后会得到:

首个非零值位于第 10 行,日期:2019-10-01
末个非零值位于第 40 行,日期:2022-04-01

方法二:tidyverse 工具包实现

如果你习惯使用dplyr等tidyverse工具,可以用链式操作完成:

library(dplyr)

# 添加行号列,筛选非零值,提取首尾行
result <- df %>%
  mutate(row_num = row_number()) %>%
  filter(`XYZ|551` != 0) %>%
  slice(c(1, n())) %>%
  select(row_num, `Row Labels`, `XYZ|551`)

# 查看结果
print(result)

输出结果会直接展示首尾两个非零值的行号、日期和数值:

# A tibble: 2 × 3
  row_num `Row Labels` `XYZ|551`
    <int> <chr>             <dbl>
1      10 2019-10-01         206
2      40 2022-04-01          33

内容的提问来源于stack exchange,提问作者user20203146

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:10:45