【问题标题】:How to split column into two in R using separate [duplicate]如何使用单独的 [重复] 在 R 中将列拆分为两列
【发布时间】:2015-11-09 15:09:35
【问题描述】:

我有一个包含这样一列位置的数据集 (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'))

但我收到此错误

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

我做错了什么?

【问题讨论】:

    标签: r tidyr


    【解决方案1】:

    指定分隔符

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

    但是,extract 看起来更干净,因为您可以同时删除“()”

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

    【讨论】:

    • 非常感谢,@nongkrong。我刚刚意识到我在原始数据框中有一些空值。有没有办法自动将它们设置为 NA?
    • @TejaK 我找不到填写 NA 的选项。我认为您可以在数据集上执行extract 而不会丢失值并绑定丢失的值。
    【解决方案2】:

    您可以使用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 应用到here
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 2015-04-03
      • 2021-12-28
      • 2018-02-05
      • 2021-10-26
      • 1970-01-01
      • 2018-06-25
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多