将字符串数据转换为数据框

Joh*_*ang 8 regex string r

我是 R 的新手,任何建议将不胜感激。

这是数据:

coordinates <- "(-79.43591570873059, 43.68015339477487), (-79.43491506339724, 43.68036886994886), (-79.43394727223847, 43.680578504490335), (-79.43388162422195, 43.68058996121469), (-79.43281544978878, 43.680808044458765), (-79.4326971769691, 43.68079658822322)"
Run Code Online (Sandbox Code Playgroud)

我希望这变成:

Latitude           Longitude
-79.43591570873059 43.68015339477487
-79.43491506339724 43.68036886994886
-79.43394727223847 43.680578504490335
-79.43388162422195 43.68058996121469
-79.43281544978878 43.680808044458765
-79.4326971769691  43.68079658822322
Run Code Online (Sandbox Code Playgroud)

Ron*_*hah 3

我们可以使用str_extract_all来自stringr

library(stringr)

df <- data.frame(Latitude = str_extract_all(coordinates, "(?<=\\()-\\d+\\.\\d+")[[1]], 
      Longitude = str_extract_all(coordinates, "(?<=,\\s)\\d+\\.\\d+(?=\\))")[[1]])
df
#            Latitude          Longitude
#1 -79.43591570873059  43.68015339477487
#2 -79.43491506339724  43.68036886994886
#3 -79.43394727223847 43.680578504490335
#4 -79.43388162422195  43.68058996121469
#5 -79.43281544978878 43.680808044458765
#6  -79.4326971769691  43.68079658822322
Run Code Online (Sandbox Code Playgroud)

Latitude捕获从左圆括号 ( () 开始的负十进制数,而Longitude捕获从逗号 ( ,) 到右圆括号 ( )) 的负十进制数。

或者没有正则表达式向前和向后并使用一起捕获它str_match_all

df <- data.frame(str_match_all(coordinates, 
                        "\\((-\\d+\\.\\d+),\\s(\\d+\\.\\d+)\\)")[[1]][, c(2, 3)])
Run Code Online (Sandbox Code Playgroud)

要将数据转换为各自的类型,您可以使用type.convert

df <- type.convert(df)
Run Code Online (Sandbox Code Playgroud)