R Data frame如何删除指定列特定字符串出现后的所有行
R数据框按指定字符串位置截取前序行解决方案
实现步骤
首先构造和你需求匹配的示例数据框:
df <- data.frame( A = c("Bob Smith", "Carl Jones", "Syndey Lewis", "total", "Adam Price", "Megan Watson"), B = c("01005", "01008", "01185", NA, "01555", "02548"), stringsAsFactors = FALSE )
base R 实现方法
# 定位A列中第一个"total"的行索引,加[1]兼容多匹配场景 total_pos <- which(df$A == "total")[1] # 截取total行之前的所有数据 result <- df[seq_len(total_pos - 1), ]
dplyr 实现方法
library(dplyr) result <- df %>% slice(seq_len(which(A == "total")[1] - 1))
输出结果
运行后得到的result即为符合要求的3行数据:
A B 1 Bob Smith 01005 2 Carl Jones 01008 3 Syndey Lewis 01185
兼容优化
如果存在数据中无匹配"total"的场景,可增加判断逻辑避免报错:
total_pos <- which(df$A == "total")[1] result <- if(!is.na(total_pos)) df[seq_len(total_pos - 1), ] else df
内容的提问来源于stack exchange,提问作者bodega18
相关产品推荐
相关产品推荐

