我試圖找出使用 str_detect 和 regex 洗掉括號及其內部所有內容的最佳方法。我找到了有助于洗掉帶有文本和數字的括號的回應,但是在檢測 $ 和值中是否有逗號的可能性時我遇到了問題。
我嘗試了以下正則運算式 \([^()]*\) ,它似乎在https://regex101.com/中有效,但是當我在示例代碼上運行它時,該列沒有應用任何更改。
任何指標將不勝感激!
Sample Data:
Example <- data.frame(Column1 = c(
"Pineapple ($1,000)",
"($50,000) Roger",
"($1,000)",
"First ($100), Second ($1,000)"))
Output <- Example %>%
mutate(Column1 = str_replace(Column1, "\([^()]*\)", ""))
設法使用 gsub 獲得輸出,但仍然想知道 tidyverse 方法是什么。
Example$Column1 <- gsub("\\([^()]*\\)", "", Example$Column1)
uj5u.com熱心網友回復:
在正則運算式中轉義時,您可以使用str_replace_all和添加另一個。\\
library(tidyverse)
Example %>% mutate(Column1 = str_replace_all(Column1, "\\([^()]*\\)", ""))
# Column1
#1 Pineapple
#2 Roger
#3
#4 First , Second
uj5u.com熱心網友回復:
我不清楚你想如何處理你有多個數字的條目。除此之外,一般來說,更方便的選擇是使用readr::parse_number,而不是使用stringr::str_detect/ stringr::str_remove。parse_number處理額外的文本、單位和千位分隔符。
如果您只想保留第一個數字(在每個條目有多個數字的情況下),您可以這樣做
library(tidyverse)
Example %>% mutate(Column1 = parse_number(Column1))
# Column1
#1 1000
#2 50000
#3 1000
#4 100
或者,如果您想保留兩個/多個數字,我建議separate_rows在使用readr::parse_number.
Example %>%
separate_rows(Column1, sep = ",\\s") %>%
mutate(Column1 = parse_number(Column1))
## A tibble: 5 × 1
# Column1
# <dbl>
#1 1000
#2 50000
#3 1000
#4 100
#5 1000
更新
要分離鍵和值,這里有一個選項;請參閱行內評論以獲取解釋:
library(tidyverse)
Example %>%
# Separate multiple comma-separated entries into rows
separate_rows(Column1, sep = ",\\s") %>%
# Swap "(value) key" > "key (value)" %>%
mutate(Column1 = str_replace(
Column1, "^(\\(. \\))\\s(\\w )$", "\\2 \\1")) %>%
# Separate "key (value)" into columns
separate(Column1, c("key", "value"), sep = "\\s", fill = "left") %>%
# Parse number
mutate(value = parse_number(value))
## A tibble: 5 × 2
# key value
# <chr> <dbl>
#1 Pineapple 1000
#2 Roger 50000
#3 NA 1000
#4 First 100
#5 Second 1000
樣本資料
Example <- data.frame(Column1 = c(
"Pineapple ($1,000)",
"($50,000) Roger",
"($1,000)",
"First ($100), Second ($1,000)"))
uj5u.com熱心網友回復:
如果我正確地滿足了您的要求,那么一個非常簡單的 base-rgsub將幫助您解決問題,包括整理雜散空間:
gsub(" ?\\([^()]*\\) ?", "", Example$Column1)
[1] "Pineapple" "Roger" "" "First, Second"
我不確定你所說的“tidyverse 方法”是什么意思:這些只是正則運算式,它們并不特定于包甚至 R。如果你更喜歡使用詳細的包裝器,你可以使用stringr::str_replace_all相同的模式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516492.html
標籤:r正则表达式细绳
