【发布时间】:2016-07-28 06:57:07
【问题描述】:
Comment
(apple (a) 100)
(orange 50)
Comment1
apple (a) 100
orange 50
我需要使用 r 将开始的左括号和结束的右括号替换为 none。
我的数据样本在“评论”字段中。我的预期输出在“Comment1”字段中。
【问题讨论】:
Comment
(apple (a) 100)
(orange 50)
Comment1
apple (a) 100
orange 50
我需要使用 r 将开始的左括号和结束的右括号替换为 none。
我的数据样本在“评论”字段中。我的预期输出在“Comment1”字段中。
【问题讨论】:
我们可以使用gsub匹配开头的括号(^\\()或结尾的括号(|)(\\)$),并替换为""。
gsub("^\\(|\\)$", "", Comment)
#[1] "apple (a) 100" "orange 50"
或者如果它基于位置,我们可以将需要的字符放在一个捕获组中,即在括号内 ((.*)) 并用反向引用 (\\1) 替换它。
sub(".(.*).", "\\1", Comment)
#[1] "apple (a) 100" "orange 50"
或者substring
substring(Comment, 2, nchar(Comment)-1)
#[1] "apple (a) 100" "orange 50"
Comment <- c("(apple (a) 100)","(orange 50)")
【讨论】: