[英]Remove row with specific number in R
我想用測試“student2”刪除行。 但是,我不想刪除“student22”、“student 23”等行。例如:
Student.Code Values
1 canada.student12 2
2 canada.student2 3 # remove
3 canada.student23 5 # keep
4 US.student2 6 # remove
5 US.student32 2
6 Aus.student87 645
7 Turkey.student25 4 #keep
我使用了代碼grepl("student2", example$Student.code, fixed = TRUE
但它也找到(刪除)了像 "student23" 這樣的行
我們可以使用grepl("student2$", example$Student.Code)
library(tidyverse)
example <- tibble::tribble(
~Student.Code, ~Values,
"canada.student12", 2L,
"canada.student2", 3L,
"canada.student23", 5L,
"US.student2", 6L,
"US.student32", 2L,
"Aus.student87", 645L,
"Turkey.student25", 4L
)
example$Student.Code
grepl("student2$", example$Student.Code)
[1] FALSE TRUE FALSE TRUE FALSE FALSE FALSE
example %>%
filter(!grepl("student2$", Student.Code))
# A tibble: 5 x 2
Student.Code Values
<chr> <int>
1 canada.student12 2
2 canada.student23 5
3 US.student32 2
4 Aus.student87 645
5 Turkey.student25 4
數據:
df <- data.frame(
Student = c("canada.student12", "canada.student2", "canada.student23","US.student2", "US.student32", "Aus.student87", "Turkey.student25"),
Value = c(2,3,5,6,2,654,5)
)
解決方案:(在基礎 R 中)
這個想法是使用grepl
來匹配數字2
出現在單詞邊界的那些值,即在正則表達式中,在\\b
處,並用否定符排除這些字符串!
:
df[!grepl("student2\\b", df$Student),]
Student Value
1 canada.student12 2
3 canada.student23 5
5 US.student32 2
6 Aus.student87 654
7 Turkey.student25 5
或者,您也可以以相反的方式 go 並匹配您想要保留的那些模式:
df[grepl("student(?=\\d{2,})", df$Student, perl = T),]
在這里,我們的想法是使用正向超前將值與student
匹配,只要它們后面緊跟至少兩位數字( \\d{2,}
)。 (請注意,使用前瞻或后瞻時,您需要包含perl = T
。)
如果您有要刪除的確切值的變量,請不要使用 grep 或 grepl。
example <- tibble::tribble(
~Student.Code, ~Values,
"canada.student12", 2L,
"canada.student2", 3L,
"canada.student23", 5L,
"US.student2", 6L,
"US.student32", 2L,
"Aus.student87", 645L,
"Turkey.student25", 4L
)
example <- example[example$Student.Code != "canada.student2",]
# or, in dplyr
example <- filter(example, Student.Code != "canada.student2")
# for multiple values
example <- filter(example, !(Student.Code %in% c("canada.student2", "US.student2")))
fixed = TRUE
不起作用,因為它的意思是“在輸入字符串中搜索這個確切的字符串”,而不是“只匹配這個確切的字符串(它必須是整個值)”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.