我有以下数据,
id <- c("case1", "case19", "case88", "case77")
vec <- c("One_20 (19)",
"tWo_20 (290)",
"Three_38 (399)",
NA)
df <- data.frame(id, vec)
> df
id vec
1 case1 One_20 (19)
2 case19 tWo_20 (290)
3 case88 Three_38 (399)
4 case77 <NA>
我想将vec
向量分成两个变量,即:txt
和。我更喜欢这样num
使用,tidyr
df |> tidyr::separate_wider_regex(vec,
c(txt = "[A-Za-z]+", num = "\\d+"),
too_few = "align_start")
# A tibble: 4 × 3
id txt num
<chr> <chr> <chr>
1 case1 One NA
2 case19 tWo NA
3 case88 Three NA
4 case77 NA NA
但是,这不是我想要的。我有以下期望:
id txt num
1 case1 One_20 19
2 case19 tWo_20 290
3 case88 Three_38 399
4 case77 <NA> NA
我在正则表达式部分犯了错误。有什么帮助可以纠正这些错误,以便我能够得到预期的表格作为输出吗?
在基础 R 中使用以下方法
sub()
:尝试
我并不总是最擅长使用正则表达式,所以尽量避免使用它。对于具有类似数据的人来说,不使用正则表达式的方法是使用
separate_wider_delim
。这会将“number_text”与“(number)”分开,然后readr::parse_number
从中提取数值num
:您也可以
parse_number
用您选择的其他方法替换,即mutate(num = as.numeric(gsub("\\(|\\)", "", num)))
。只要您的正则表达式构造良好,您就不需要使用任何外部包或花哨的单行程序。
针对您的特殊需要,此模式有效:
然后,您可以直接使用它来分配给 df 中的必要列,或者使用 sub:
或者,如果您想避免多次运行正则表达式,请使用 regmatches/regexec 和 lapply: