如何在R中使用separate将列拆分为两个?

4

我有一个数据集,其中一列是像这样的位置信息(41.797634883,-87.708426986)。我想将其拆分为纬度和经度。我尝试使用tidyr包中的separate方法。

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

但是我遇到了这个错误

Error: Values not split into 2 pieces at 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 

我哪里做错了?
3个回答

11

指定分隔字符

dataframe %>% separate(Location, c('Latitude', 'Longitude'), sep=",")

但是,extract 看起来更清晰,因为你可以同时删除 "()"。

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

非常感谢,@nongkrong。我刚刚意识到原始数据框中有一些空值。是否有一种自动将它们设置为NA的方法? - ytk
@TejaK 我找不到用NA填充的选项。我认为你可以在没有缺失值的数据集上执行extract,然后行绑定缺失的数据。 - Rorschach

6
您可以使用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

.@akrun - 如何将 base R 应用于这里 - Chetan Arvind Patil

2

或者,您可以使用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 <- 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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接