我想从字符串中删除括号和括号。我得到了所需的结果,但是正在寻找更紧凑的方法。
Test <- c("-0.158)", "0.426)", "1.01)", "1.6)", "2.18)", "2.77]")
stringr::str_replace(
string = Test
, pattern = "\\)"
, replacement = ""
)
# [1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77]"
stringr::str_replace(
string = Test
, pattern = "\\]"
, replacement = ""
)
# [1] "-0.158)" "0.426)" "1.01)" "1.6)" "2.18)" "2.77"
stringr::str_replace(
string = stringr::str_replace(
string = Test
, pattern = "\\]"
, replacement = ""
)
, pattern = "\\)"
, replacement = ""
)
# [1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
想知道是否可以通过单个命令获得它
stringr::str_replace(
string = Test
, pattern = "\\)^]"
, replacement = ""
)
已编辑
找到了一个非常简单的解决方案
readr::parse_number(Test)
[1] -0.158 0.426 1.010 1.600 2.180 2.770.
答案 0 :(得分:2)
我们可以使用|
gsub("\\)|\\]", "", Test)
#[1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
或者不要将括号放在[]
gsub("[][()]", "", Test)
#[1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
如果我们要提取数据而不是删除数据,请使用gregexpr/regmatches
中的base R
或str_extract
中的stringr
来检查数字可以以{{ 1}},并包含-
.