-1

I have a column with a string value:

"geo:lat:55.892994,lng:10.510947,address:content:NA"

And I want to have twonew columnn with:

column1: 55.892994       
column2: 10.510947

Would you help me with R code?

I was trying to use str_extract and str_split, but I cannot seem to achieve the result

1
  • 2
    What exactly did you try, and what about it didn't work? Commented Feb 13, 2023 at 1:44

5 Answers 5

1
string <- "geo:lat:55.892994,lng:10.510947,address:content:NA"
library(tidyverse)

data.frame(string=string) %>%
  extract(string, c("lat", "lng"), "lat:([0-9.]+),lng:([0-9.]+)",convert = TRUE)
#>        lat      lng
#> 1 55.89299 10.51095

Created on 2023-02-12 with reprex v2.0.2

Sign up to request clarification or add additional context in comments.

Comments

0

Please check the below code

library(tidyverse)
library(stringr)

string <- "geo:lat:55.892994,lng:10.510947,address:content:NA"

data.frame(string=string) %>% 
transmute(column1=str_remove_all(str_extract_all(string, '.*\\d+(?=\\d\\,lng)'),'[a-zA-Z:]'),
          column2=str_remove_all(str_extract_all(string, '(?<=\\,).*\\d+(?=\\d\\,address)'),'[a-zA-Z:]') 
                                                                  )

Created on 2023-02-12 with reprex v2.0.2

   column1  column2
1 55.89299 10.51094

Comments

0

You can use sub from base R.

data <- data.frame(xy="geo:lat:55.892994,lng:10.510947,address:content:NA")

data$lat <- sub('.*lat:(\\d+\\.\\d+).*', '\\1', data$xy)
data$lng <- sub('.*lng:(\\d+\\.\\d+).*', '\\1', data$xy)

See help(regex) for details.

Comments

0

Try the following regex.

library(stringr)
s="geo:lat:55.892994,lng:10.510947,address:content:NA"
str_match(s,"lat:([0-9]{2}.[0-9]{6}).*?lng:([0-9]{2}.[0-9]{6})")

Outputs

     [,1]                          [,2]        [,3]       
[1,] "lat:55.892994,lng:10.510947" "55.892994" "10.510947"

Comments

0

You can use gregexpr with [0-9.]+ to find the numbers and regmatches to extract them.

cbind(x, do.call(rbind, regmatches(x$s, gregexpr("[0-9.]+", x$s))))
#                                                   s         1         2
#1 geo:lat:55.892994,lng:10.510947,address:content:NA 55.892994 10.510947
#2 geo:lat:57.892994,lng:14.510947,address:content:NA 57.892994 14.510947

Data

x <- data.frame(s = c("geo:lat:55.892994,lng:10.510947,address:content:NA",
                      "geo:lat:57.892994,lng:14.510947,address:content:NA"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.