[英]removing characters in brackets of indefinite length from end of column names in R
I have some column names in a df as follows:我在 df 中有一些列名,如下所示:
column1 (-)
column2 (unwantedstring)
column3
column4 (4)
Note that some columns do not have unwanted brackets on the end and should be kept the same.请注意,某些列的末尾没有不需要的括号,应保持不变。
I want to get rid of the brackets at the end and anything inside it (along with the space before the opening brackets) to get:我想去掉最后的括号和里面的任何东西(以及左括号之前的空间)以获得:
column1
column2
column3
column4
Am I on the right track with the below?我在下面的正确轨道上吗?
df <- df %>%
rename_with(~str_remove(.x, " \(*\)$"))
Any help would be appreciated任何帮助,将不胜感激
You may use sub
here for a base option:您可以在此处使用
sub
作为基本选项:
x <- c("column1 (-)", "column2 (unwantedstring)", "column3", "column4 (4)")
output <- sub("\\s+\\(.*\\)$", "", x)
output
[1] "column1" "column2" "column3" "column4"
You can also use the following solution, however, it's a bit complicated.您也可以使用以下解决方案,但是,它有点复杂。
trimws(regmatches(x, regexpr("\\([^()]\\](SKIP*)(FAIL*)|(?<!\\()[^()]*(?!\\))", x, perl = TRUE)))
[1] "column1" "column2" "column3" "column4"
Thanks for the data Tim Biegeleisen感谢蒂姆·比格莱森提供的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.