3

Based on the advice here: Find location of character in string, I tried this:

> gregexpr(pattern ='$',"data.frame.name$variable.name")
[[1]]
[1] 30
attr(,"match.length")
[1] 0
attr(,"useBytes")
[1] TRUE

But it didn't work; note:

> nchar("data.frame.name$variable.name")
[1] 29

How do you find the location of $ in this string?

Community
  • 1
  • 1
gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79

2 Answers2

9

The problem is that $ is the end-of-string marker in the regex. Try this instead:

> gregexpr(pattern ='\\$',"data.frame.name$variable.name")
[[1]]
[1] 16
attr(,"match.length")
[1] 1
attr(,"useBytes")
[1] TRUE

... which gives the right answer - i.e. 16.

Simon
  • 10,679
  • 1
  • 30
  • 44
3

Here's one solution using strsplit and which

> which(strsplit("data.frame.name$variable.name", "")[[1]]=="$")
[1] 16
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • 1
    Thanks! That's a very simple, clever solution. – gung - Reinstate Monica Oct 06 '13 at 23:11
  • 1
    BTW, you should add this as an answer to the other thread; it's more straightforward than the existing answer. – gung - Reinstate Monica Oct 06 '13 at 23:14
  • 1
    FWIW, I gave the check to Simon b/c he also explained why my code wasn't working, but I'll use this solution since it's simpler. – gung - Reinstate Monica Oct 06 '13 at 23:31
  • 2
    Although Jilber's solution is a nice alternative, I would go for Simon's approach. Given that the reader has some experience with R, the code with `gregexpr` is easier to understand and is most likely more efficient. I assume that `gregexpr` just iterates through the string, whereas `strsplit` splits the whole string into single characters and then stores the result. Although performance may not be an issue here, I still consider `gregexpr` as the better approach. – cryo111 Oct 07 '13 at 00:00