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

如何筛选含nl.audio的行及上下行并迁移至新数据框?

解决方案

以下两种方法均可实现需求,分别基于基础R和tidyverse工具链:

方法1:基础R实现

# 1. 定位所有行名包含`nl.audio`的行索引
audio_indices <- which(grepl("nl.audio", rownames(dat2)))

# 2. 收集目标索引:当前行、上一行、下一行
target_indices <- unique(c(audio_indices - 1, audio_indices, audio_indices + 1))

# 3. 过滤超出数据框范围的索引(避免0或大于总行数的无效索引)
target_indices <- target_indices[target_indices >= 1 & target_indices <= nrow(dat2)]

# 4. 按原顺序排序索引,保持行的原始排列
target_indices <- sort(target_indices)

# 5. 提取目标行到新数据框
new_dat <- dat2[target_indices, , drop = FALSE]

方法2:tidyverse实现

library(tidyverse)

# 1. 转换数据结构,添加行号和行名列
dat2_tidy <- dat2 %>%
  mutate(row_num = row_number()) %>%
  rownames_to_column("row_name")

# 2. 获取所有包含`nl.audio`的行号
audio_rows <- dat2_tidy %>%
  filter(str_detect(row_name, "nl.audio")) %>%
  pull(row_num)

# 3. 收集目标行号:当前行、上一行、下一行
target_rows <- unique(c(audio_rows - 1, audio_rows, audio_rows + 1))

# 4. 提取并整理目标行,恢复原行名格式
new_dat_tidy <- dat2_tidy %>%
  filter(row_num %in% target_rows) %>%
  arrange(row_num) %>%
  select(-row_num) %>%
  column_to_rownames("row_name")

关键说明

  • 使用grepl/str_detect匹配行名中的nl.audio关键词
  • 通过unique避免重复提取相邻行(比如两个音频行连续时,中间行不会被重复选中)
  • 过滤边界索引防止出现无效行引用
  • 排序索引保证新数据框的行顺序与原数据框一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:24:08