[英]Combination Regmatches and Replacement for specific Character
我試過替換與特定字符匹配或后跟“BT”的字符,但我的代碼失敗了。 這是我的代碼:
df <- data.frame(
exposure = c("123BT", "113BB", "116BB", "117BT")
)
df %>%
mutate(
exposure2 = case_when(exposure == regmatches("d+\\BT") ~ paste0("-", exposure),
TRUE ~ exposure)
)
錯誤是:
Error: Problem with `mutate()` column `exposure2`.
i `exposure2 = case_when(...)`.
x argument "m" is missing, with no default
Run `rlang::last_error()` to see where the error occurred.
而我的目標是:
df <- data.frame(
exposure = c("123BT", "113BB", "116BB", "117BT"),
exposure2 = c(-123, 113, 116, -117)
)
我建議您使用庫stringr
,您可以使用正則表達式(\\d)+
提取您的數字:
library(stringr)
library(dplyr)
df %>%
mutate(
exposure2 = case_when(str_detect(exposure,"BT") ~ paste0("-", str_extract(exposure, "(\\d)+")),
TRUE ~ str_extract(exposure, "(\\d)+"))
)
Output:
exposure exposure2
1 123BT -123
2 113BB 113
3 116BB 116
4 117BT -117
如果您仍然喜歡使用regmatches
,您可以獲得相同的結果:
df %>%
mutate(
exposure2 = case_when(exposure %in% regmatches(exposure, regexpr("\\d+BT", exposure)) ~ paste0("-", regmatches(exposure, regexpr("\\d+", exposure))),
TRUE ~ regmatches(exposure, regexpr("\\d+", exposure)))
)
首先,您可以在dplyr::mutate
中輕松實現一個簡潔的解決方案。 使用gsub
我們刪除字符並將結果強制為as.integer
。 結果,我們根據字符串是否包含"BT"
乘以1
或-1
; 為此,我們使用grepl
(給出布爾值)並添加1L
(強制轉換為整數)以獲得索引1
或2
。
c(1, -1)[grepl('BT', df$exposure) + 1L]*as.integer(gsub('\\D', '', df$exposure))
# [1] -123 113 116 -117
以上是推薦的解決方案。 您設想的解決方案要復雜得多,因為它處理信息的效率不是很高。 我在一個小f
1中實現邏輯來演示。
f <- \(x) {
rm <- regmatches(x, regexpr("\\d+BT", x))
o <- gsub('\\D', '', x)
o <- ifelse(x %in% rm, paste0('-', o), o)
as.integer(o)
}
f(df$exposure)
# [1] -123 113 116 -117
1注意:對於正regexpr
regmatches
信息。 正則表達式實際上應該看起來像"\\d+BT"
。
數據:
df <- structure(list(exposure = c("123BT", "113BB", "116BB", "117BT"
)), class = "data.frame", row.names = c(NA, -4L))
library(readr)
(-1)^grepl('BT', df$exposure) * parse_number(df$exposure)
[1] -123 113 116 -117
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.