Erica Erica - 28 days ago 14
R Question

Need to extract latitude and longitude from a text string

I have a dataframe that contains latitude and longitude in this format (41.848374, -74.099412). I need to put latitde in 1 column and longitude in another. I have tried various R functions including gub, substr, sub and have not been able to solve this problem. Any help would be appreciated.

Answer

We can use a combination of read.table and gsub. Remove the () part with gsub and use read.table with sep="," to read the strings as a two column data.frame.

read.table(text=gsub("[()]", "", str1), header=FALSE, sep=",")
#      V1        V2
#1 41.84837 -74.09941

data

str1 <- '(41.848374, -74.099412)'
Comments