如何在R中使用单独的

如何在R中使用单独的,r,tidyr,R,Tidyr,我有一个数据集,其中有这样一列位置(41.797634883,-87.708426986)。我试着把它分成纬度和经度。我尝试使用tidyr包中的单独方法 library(dplyr) library(tidyr) df <- data.frame(x = c('(4, 9)', '(9, 10)', '(20, 100)', '(100, 200)')) df %>% separate(x, c('Latitude', 'Longitude')) 我做错了什么?指定分隔字符 dat

我有一个数据集,其中有这样一列位置(41.797634883,-87.708426986)。我试着把它分成纬度和经度。我尝试使用tidyr包中的单独方法

library(dplyr)
library(tidyr)
df <- data.frame(x = c('(4, 9)', '(9, 10)', '(20, 100)', '(100, 200)'))
df %>% separate(x, c('Latitude', 'Longitude'))

我做错了什么?

指定分隔字符

dataframe %>% separate(Location, c('Latitude', 'Longitude'), sep=",")
但是,
extract
看起来更干净,因为您可以同时删除“()”

dataframe %>% extract(x, c("Latitude", "Longitude"), "\\(([^,]+), ([^)]+)\\)")

或者,您可以使用stringi包获取数字并创建数据帧

library(stringi)

data.frame(lat = stri_extract_first(mydf$x, regex = "\\d{1,}.\\d{1,}"),
           lon = stri_extract_last(mydf$x, regex = "\\d{1,}.\\d{1,}"))

#           lat          lon
#1 41.797634883 87.708426986
#2 41.911390159 87.732635428
#3 41.672925444 87.642819748
#4 41.759925265 87.698867528
#5 41.856122914 87.717449534
#6 41.900794625 87.671240384
资料


mydf您可以使用
base R
执行此操作。删除带有
gsub
的括号,并使用
read.table
读取列“x”(基于@jazzuro的示例),将其分为两列

 read.table(text=gsub('[()]', '', mydf$x), 
         sep=",", col.names=c('Latitute', 'Longitude'))
 #   Latitute Longitude
 #1 41.79763 -87.70843
 #2 41.91139 -87.73264
 #3 41.67293 -87.64282
 #4 41.75993 -87.69887
 #5 41.85612 -87.71745
 #6 41.90079 -87.67124

非常感谢,@nongkrong。我刚刚意识到在原始数据帧中有一些空值。有没有办法自动将这些设置为NA?@TejaK我找不到填充NA的选项。我认为您可以在数据集上执行
提取
,而不丢失值,并对丢失的值进行行绑定。@akrun-如何将
基R
应用于?
mydf <- structure(list(x = structure(c(3L, 6L, 1L, 2L, 4L, 5L), .Label = c("(41.672925444, -87.642819748)", 
"(41.759925265, -87.698867528)", "(41.797634883, -87.708426986)", 
"(41.856122914, -87.717449534)", "(41.900794625, -87.671240384)", 
"(41.911390159, -87.732635428)"), class = "factor")), .Names = "x", row.names = c(NA, 
-6L), class = "data.frame")
 read.table(text=gsub('[()]', '', mydf$x), 
         sep=",", col.names=c('Latitute', 'Longitude'))
 #   Latitute Longitude
 #1 41.79763 -87.70843
 #2 41.91139 -87.73264
 #3 41.67293 -87.64282
 #4 41.75993 -87.69887
 #5 41.85612 -87.71745
 #6 41.90079 -87.67124