특정 문자열을 포함하는 행 필터링
문자열이 포함된 행을 기준으로 데이터 프레임을 필터링해야 합니다.RTB.
사용 중dplyr.
d.del <- df %>%
group_by(TrackingPixel) %>%
summarise(MonthDelivery = as.integer(sum(Revenue))) %>%
arrange(desc(MonthDelivery))
나는 그 기능을 사용할 수 있다는 것을 알고 있습니다.filter에dplyr끈의 내용물을 확인하기 위해 정확히 어떻게 말해야 할지 모르겠습니다.
특히 칼럼의 내용을 확인하고 싶습니다.TrackingPixel문자열에 레이블이 포함된 경우RTB결과에서 행을 제거합니다.
질문에 대한 답변은 이미 위의 댓글에 @latemail에 의해 게시되었습니다.의 두 번째 및 이후 인수에 정규식을 사용할 수 있습니다.filter다음과 같이:
dplyr::filter(df, !grepl("RTB",TrackingPixel))
당신이 원본 데이터를 제공하지 않았기 때문에, 나는 그것을 이용하여 장난감 예시를 추가할 것입니다.mtcars데이터 세트여러분이 마츠다나 도요타가 생산하는 자동차에만 관심이 있다고 상상해 보세요.
mtcars$type <- rownames(mtcars)
dplyr::filter(mtcars, grepl('Toyota|Mazda', type))
mpg cyl disp hp drat wt qsec vs am gear carb type
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag
3 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla
4 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Toyota Corona
반대로, 즉 도요타와 마쓰다 자동차를 제외하고 싶다면,filter명령은 다음과 같습니다.
dplyr::filter(mtcars, !grepl('Toyota|Mazda', type))
해결책
사용할 수 있습니다.str_detect의stringr패키지에 포함됨tidyverse꾸러미 str_detect돌아온다True또는False지정된 벡터에 특정 문자열이 포함되어 있는지 여부.이 부울 값을 사용하여 필터링할 수 있습니다.자세한 내용은 stringr 소개를 참조하십시오.stringr꾸러미
library(tidyverse)
# ─ Attaching packages ──────────────────── tidyverse 1.2.1 ─
# ✔ ggplot2 2.2.1 ✔ purrr 0.2.4
# ✔ tibble 1.4.2 ✔ dplyr 0.7.4
# ✔ tidyr 0.7.2 ✔ stringr 1.2.0
# ✔ readr 1.1.1 ✔ forcats 0.3.0
# ─ Conflicts ───────────────────── tidyverse_conflicts() ─
# ✖ dplyr::filter() masks stats::filter()
# ✖ dplyr::lag() masks stats::lag()
mtcars$type <- rownames(mtcars)
mtcars %>%
filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl disp hp drat wt qsec vs am gear carb type
# 1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4
# 2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag
# 3 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla
# 4 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Toyota Corona
Stringr의 좋은 점들
우리는 오히려 사용해야 합니다.stringr::str_detect()보다base::grepl()이것은 다음과 같은 이유가 있기 때문입니다.
- 에서 제공하는 기능
stringr접두사로 시작하는 패키지str_코드를 더 쉽게 읽을 수 있습니다. - 의 함수에 대한 첫 번째 인수
stringrpackage는 항상 data.frame(또는 값)이고 매개 변수가 옵니다.(파올로에게 감사합니다)
object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"
벤치마크
벤치마크 테스트 결과는 다음과 같습니다.대규모 데이터 프레임의 경우,str_detect더 빠릅니다.
library(rbenchmark)
library(tidyverse)
# The data. Data expo 09. ASA Statistics Computing and Graphics
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728 29
benchmark(
"str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
"grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
replications = 10,
columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2 grepl 10 16.480 1.513 16.195 0.248
# 1 str_detect 10 10.891 1.000 9.594 1.281
이 대답은 다른 대답과 비슷하지만 선호하는 대답을 사용합니다.stringr::str_detect그리고 dplyrrownames_to_column.
library(tidyverse)
mtcars %>%
rownames_to_column("type") %>%
filter(stringr::str_detect(type, 'Toyota|Mazda') )
#> type mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 2 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 3 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
#> 4 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
reprex 패키지(v0.2.0)에 의해 2018-06-26에 생성되었습니다.
여기 또 있습니다.dplyr솔루션, 사용filter(if_all/if_any)장점은 두 개 이상의 열로 쉽게 확장할 수 있다는 것입니다.아래는 열에 지정된 문자열이 있는 행을 필터링하는 방법을 보여줍니다.diamonds예를 들어, "V" 문자열을 찾습니다.
dplyr 구문의 변경 사항을 반영하도록 편집합니다(>=dplyr vs. 1.0.10).이전 사용across(현재는 더 이상 사용되지 않음) 그리고 심지어 그 이전에도.filter_all또는filter_any(제한 없음).
열이 조건을 충족하는 행 제거
library(dplyr)
## with if_any
ggplot2::diamonds %>%
## NB ! needs to come before if_any
filter(!if_any(everything(), ~ grepl('V', .))) %>%
head()
#> # A tibble: 6 × 10
#> carat cut color clarity depth table price x y z
#> <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43
#> 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31
#> 3 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75
#> 4 0.3 Good J SI1 64 55 339 4.25 4.28 2.73
#> 5 0.22 Premium F SI1 60.4 61 342 3.88 3.84 2.33
#> 6 0.31 Ideal J SI2 62.2 54 344 4.35 4.37 2.71
## or with if_all
ggplot2::diamonds %>%
filter(if_all(everything(), ~ !grepl('V', .))) %>%
head()
#> # A tibble: 6 × 10
#> carat cut color clarity depth table price x y z
#> <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43
#> 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31
#> 3 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75
#> 4 0.3 Good J SI1 64 55 339 4.25 4.28 2.73
#> 5 0.22 Premium F SI1 60.4 61 342 3.88 3.84 2.33
#> 6 0.31 Ideal J SI2 62.2 54 344 4.35 4.37 2.71
열이 조건을 충족하는 행 필터링
## The new syntax makes it also easy to positively filter rows
## where one columns fulfils a condition
ggplot2::diamonds %>%
filter(if_any(everything(), ~ grepl('V',.))) %>%
head()
#> # A tibble: 6 × 10
#> carat cut color clarity depth table price x y z
#> <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31
#> 2 0.29 Premium I VS2 62.4 58 334 4.2 4.23 2.63
#> 3 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48
#> 4 0.24 Very Good I VVS1 62.3 57 336 3.95 3.98 2.47
#> 5 0.26 Very Good H SI1 61.9 55 337 4.07 4.11 2.53
#> 6 0.22 Fair E VS2 65.1 61 337 3.87 3.78 2.49
Akruns의 제안에 기반한 추가 옵션 - rowSums 및 부분 집합을 사용하여 논리 벡터를 만듭니다.기본 R에만 해당됩니다.이는 열에 우리가 찾는 값이 정확히 포함되어 있을 때 특히 유용하고 우아합니다. (또는 아래와 같은 간단한 조건문으로 2차원 배열을 만들 수 있는 경우)df1 == "no_data")
## this is very easy when the expected value is EXACTLY the string
df1 <- structure(list(time = c("1:00", "2:00", "no_data", "3:00"), speed = c("30", "no_data", "no_data", "50"), wheels = c("no_data", "18", "no_data", "18")), .Names = c("time", "speed", "wheels"), class = "data.frame", row.names = c(NA, -4L))
df1[rowSums(df1 == "no_data") == 0, , drop = FALSE]
#> time speed wheels
#> 4 3:00 50 18
## it's a bit more verbose when the expected value just CONTAINS the string
mtcars$type <- rownames(mtcars)
mtcars[rowSums(apply(mtcars, 2, \(x) grepl('Toyota|Mazda', x))) > 0, , drop = FALSE] |> head()
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
#> Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
#> Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
#> type
#> Mazda RX4 Mazda RX4
#> Mazda RX4 Wag Mazda RX4 Wag
#> Toyota Corolla Toyota Corolla
#> Toyota Corona Toyota Corona
언급URL : https://stackoverflow.com/questions/22850026/filter-rows-which-contain-a-certain-string
'programing' 카테고리의 다른 글
| 작은 첨자를 가진 요소를 포함하여 모든 중복 행 찾기 (0) | 2023.06.04 |
|---|---|
| Python에서 객체의 속성을 열거하는 방법은 무엇입니까? (0) | 2023.06.04 |
| 표준 오류 스트림에서 로깅을 사용하지 않도록 설정하는 방법은 무엇입니까? (0) | 2023.06.04 |
| 명령줄 인수를 RCMD BATCH에 전달하는 중 (0) | 2023.06.04 |
| 명령줄을 사용하여 postgres 백업 파일을 복원하시겠습니까? (0) | 2023.06.04 |