gung - Reinstate Monica
gung - Reinstate Monica

Reputation: 11903

Find location of $ in string

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?

Upvotes: 3

Views: 329

Answers (2)

Simon
Simon

Reputation: 10841

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.

Upvotes: 9

Jilber Urbina
Jilber Urbina

Reputation: 61204

Here's one solution using strsplit and which

> which(strsplit("data.frame.name$variable.name", "")[[1]]=="$")
[1] 16

Upvotes: 3

Related Questions