在R语言中如何删除NA值所在行及其上下相邻的行?
R语言实现删除NA行及上下相邻行的方法
实现思路
- 首先定位
Center_x、Center_y两列中任意一列存在NA的行的索引 - 对每个NA行的索引,扩展出其前一行、当前行、后一行三个索引,过滤掉超出数据集行范围的无效索引
- 从原数据中剔除所有待删除索引对应的行,得到最终结果
代码实现
方法1:tidyverse版本(适合大数据集高效处理)
library(tidyverse) # 构造样例数据(实际使用时替换为你的数据集即可) df <- tibble( Center_x = c(200.3, NA, 300, 400.1, 200, 100, 200), Center_y = c(400, 200.2, 100, 450, 100, NA, 100) ) # 定位NA行索引 na_rows <- which(is.na(df$Center_x) | is.na(df$Center_y)) # 生成待删除的所有行索引,去重且过滤无效值 del_rows <- unique(c(na_rows - 1, na_rows, na_rows + 1)) del_rows <- del_rows[del_rows >= 1 & del_rows <= nrow(df)] # 筛选保留行 result <- df[-del_rows, ]
运行后result的输出和预期结果完全一致:
# A tibble: 1 × 2 Center_x Center_y <dbl> <dbl> 1 400.1 450
方法2:base R版本(无需额外安装包)
# 构造样例数据 df <- data.frame( Center_x = c(200.3, NA, 300, 400.1, 200, 100, 200), Center_y = c(400, 200.2, 100, 450, 100, NA, 100) ) na_rows <- which(is.na(df$Center_x) | is.na(df$Center_y)) del_rows <- unique(c(na_rows - 1, na_rows, na_rows + 1)) del_rows <- del_rows[del_rows >= 1 & del_rows <= nrow(df)] result <- df[-del_rows, ]
两种方法均采用向量化操作,没有逐行遍历,处理大型数据集时效率有保障。
内容的提问来源于stack exchange,提问作者Naomi
相关产品推荐
相关产品推荐

