Length of location sequence (specified as a string) in R

I have a list of geolocation sequences. Each item on my list looks like this:

> "[[1.2,2.2],[-1.12,3.45],[12.311,-1.34],[-12.32,33.333]]"

      

I would like to be able to get the length of the sequence (4 in the above example). could you help me? I tried to use regular expressions but couldn't succeed.

Thank you in advance!

+3


source to share


3 answers


Like some people in the comments, you can count the number of times a certain character appears in your sequences. This assumes that the data is well-formed and consistent. For example:

library(stringr)
x <- "[[1.2,2.2],[-1.12,3.45],[12.311,-1.34],[-12.32,33.333]]"
str_count(x, "\\[") - 1 #subtract 1 since there are two opening [

      



gives:

> str_count(x, "\\[") - 1
[1] 4

      

+1


source


If you don't want to download the library



str <- "[[1.2,2.2],[-1.12,3.45],[12.311,-1.34],[-12.32,33.333]]"
nchar(str)-nchar(gsub("\\]", "", str))-1

      

+1


source


You can use:

\[[^[]

      

And then count the matches.

Demo

In R:

> x <- "[[1.2,2.2],[-1.12,3.45],[12.311,-1.34],[-12.32,33.333]]"
> length(gregexpr("\\[[^\\[]",x)[[1]])
[1] 4

      

0


source







All Articles