Удалить несколько знаков препинания, разбросанных по всей строке - PullRequest
0 голосов
/ 27 ноября 2018

Это имена столбцов по умолчанию.

columnNames
[1] "chain:1.theta[1]" "chain:1.theta[2]" "chain:1.theta[3]" "chain:1.theta[4]"

Мне бы хотелось, чтобы columnNames было:

[1] "theta1" "theta2" "theta3" "theta4"

Я хотел бы сделать это, используя одно регулярное выражение.Я пробовал несколько разных подходов, но безуспешно.

> gsub('chain:[[:digit:]][[:punct:]]', '', columnNames)
[1] "theta[1]" "theta[2]" "theta[3]" "theta[4]"

> gsub('chain:[[:digit:]].\\[|\\]', '', columnNames)
[1] "chain:1.theta[1" "chain:4.theta[2" "chain:1.theta[3" "chain:4.theta[4"

> gsub('(?=.*chain:[[:digit:]][[:punct:]])(?=.*"\\[|\\])', '', columnNames, perl = TRUE)
[1] "chain:1.theta[1]" "chain:4.theta[2]" "chain:1.theta[3]" "chain:4.theta[4]

> gsub('(?!theta\\[[:digit:]])', '', columnNames, perl = TRUE)
Error in gsub("(?!theta\\[[:digit:]])", "", columnNames, perl = TRUE) : 
  invalid regular expression '(?!theta\[[:digit:]])'
In addition: Warning message:
In gsub("(?!theta\\[[:digit:]])", "", columnNames, perl = TRUE) :
  PCRE pattern compilation error
    'POSIX named classes are supported only within a class'
    at '[:digit:]])'

1 Ответ

0 голосов
/ 27 ноября 2018
gsub(".*\\.(.*)\\[(\\d+)\\]", "\\1\\2", columnNames)
[1] "theta1" "theta2" "theta3" "theta4"

, где .*\\. соответствует всему, включая точку, (.*) соответствует theta в этом случае и (\\d+) тета-числам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...