I am trying to access all the characters within a pair of brackets for some character vector (so that I can then reverse them). R doesn’t seem to be treating ")" the same as a normal character. I first tried:
solution <- function(inputString) {
print(a <- unlist(strsplit(x=inputString,split="")))
print(bracket.indices <- grep(pattern="(|)",x=a))
}
I tried this with the following input string:
"(bar)"
What I’m wanting this bit of my code to do is simply give me the index number of the bracket characters so that I can later operate on the characters inside. I can’t manage it though. I run my code and I get:
[1] "(" "b" "a" "r" ")"
[1] 1 2 3 4 5
The first one is right. The second one not. I should have 1 and 5. Playing around a bit, I can see that something is going on with how R is taking the brackets. If I just my function to just have one bracket in grep:
solution <- function(inputString) {
print(a <- unlist(strsplit(x=inputString,split="")))
print(bracket.indices <- grep(pattern="(",x=a))
}
I get:
Error in grep(pattern = "(", x = a) :
invalid regular expression '(', reason 'Missing ')''
In addition: Warning message:
In grep(pattern = "(", x = a) :
Error in grep(pattern = "(", x = a) :
invalid regular expression '(', reason 'Missing ')''
I thought, "OK, grep is a lost cause, so let me just play around with a for loop and see if I can do it that way, but that gives unlooked-for results as well:
solution <- function(inputString) {
print(a <- unlist(strsplit(x=inputString,split="")))
for (i in 1:length(a)) {
if (a[i] == "(" | a[i] == ")") {
bracket.indices <- which(a[i] == "(" | a[i] == ")")
}
print(bracket.indices)
}
}
Result:
solution("(bar)")
[1] "(" "b" "a" "r" ")"
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
I’ve been away from R for a while, and it shows. Any help guys?
>Solution :
We can add escape characters \\ to search specifically for ( or ).
solution <- function(inputString) {
print(a <- unlist(strsplit(x=inputString,split="")))
print(bracket.indices <- grep(pattern="\\(|\\)",x=a))
}
Output
solution("(bar)")
# [1] "(" "b" "a" "r" ")"
# [1] 1 5